XML文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.myapplication.MyGLSurfaceView
android:id="@+id/gl_surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="@+id/image_view"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_margin="16dp"
android:background="#33000000"
android:contentDescription="FBO截图预览" />
<Button
android:id="@+id/capture_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"
android:text="捕获FBO图像"
android:padding="12dp" />
</RelativeLayout>
Activity代码
class MainActivity : AppCompatActivity() {
private lateinit var glSurfaceView: MyGLSurfaceView
private lateinit var imageView: ImageView
private lateinit var captureButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
glSurfaceView = findViewById(R.id.gl_surface_view)
imageView = findViewById(R.id.image_view)
captureButton = findViewById(R.id.capture_button)
captureButton.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
when(event?.action){
MotionEvent.ACTION_DOWN -> {
getFrameBufferBitmap()?.let {
imageView.setImageBitmap(it)
}
}
MotionEvent.ACTION_UP -> {
getFrameBufferBitmap()?.let {
imageView.setImageBitmap(null)
}
}
else -> {
}
}
return true
}
})
}
private fun getFrameBufferBitmap() : Bitmap? {
return glSurfaceView?.getFrameBufferBitmap()
}
}
自定义GLSurfaceView代码
class MyGLSurfaceView(context: Context, attrs: AttributeSet) : GLSurfaceView(context, attrs) {
private var mRenderer = MyGLRenderer(context)
init {
setEGLContextClientVersion(3)
setRenderer(mRenderer)
renderMode = RENDERMODE_WHEN_DIRTY
}
fun getFrameBufferBitmap(): Bitmap? {
return mRenderer?.getFrameBufferBitmap()
}
}
自定义GLSurfaceView.Renderer代码
class MyGLRenderer(private val mContext: Context) : GLSurfaceView.Renderer {
private var mDrawData: DrawData? = null
private var mWidth = 0
private var mHeight = 0
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
GLES30.glClearColor(0.0f, 0.5f, 0.5f, 1.0f)
mDrawData = DrawData().apply {
initShader()
initVertexBuffer()
initTexture0(mContext, R.drawable.pic)
initTexture1(mContext, R.drawable.bitmap_shader)
}
}
override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
GLES30.glViewport(0, 0, width