SurfaceTexture
在 Android 中是一个允许应用程序捕获并显示实时图形内容的类,通常用于显示相机预览或从 OpenGL ES 渲染到 SurfaceView
。以下是对 SurfaceTexture
使用的一个简化代码示例,以及对每一步操作的分析和注释:
创建 SurfaceTexture
// 创建一个 SurfaceTexture 对象
SurfaceTexture surfaceTexture = new SurfaceTexture(0);
// 设置 SurfaceTexture 的回调监听器
surfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {
@Override
public void onFrameAvailable(SurfaceTexture st) {
// 当新的一帧图像准备好可以被消费时,此方法会被调用
// 这通常意味着可以绘制图像到 Surface 上了
}
});
配置 SurfaceTexture
// 绑定一个 Surface 到 SurfaceTexture
// 这个 Surface 将用于实际显示图像内容
Surface surface = new Surface(surfaceTexture);
// 将 Surface 与 SurfaceView 关联
SurfaceView surfaceView = findViewById(R.id.surface_view);
surfaceView.getHolder().setSurface(surface);
处理 SurfaceTexture 的帧
// 在渲染循环中,或在 SurfaceTexture 的回调中,定期调用 updateTexImage
public void drawFrame() {
if (surfaceTexture != null) {
surfaceTexture.updateTexImage(); // 获取新的图像帧数据
// 此时可以进行 OpenGL ES 渲染或其他处理
}
}
OpenGL ES 渲染
// 在 OpenGL ES 渲染循环中,使用 SurfaceTexture 作为纹理进行渲染
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
surfaceTexture.attachToGLContext(textureId); // 将 SurfaceTexture 绑定到 OpenGL ES 上下文
// 执行 OpenGL ES 绘制命令
GLES20.glDrawElements(...);
surfaceTexture.detachFromGLContext(textureId); // 从 OpenGL ES 上下文中分离 SurfaceTexture
生命周期管理
@Override
protected void onPause() {
super.onPause();
if (surfaceTexture != null) {
// 释放 SurfaceTexture 相关资源
surfaceTexture.release();
}
if (surfaceView != null) {
// 释放 SurfaceView 相关资源
surfaceView.getHolder().getSurface().release();
}
}
@Override
protected void onResume() {
super.onResume();
// 重新初始化 SurfaceTexture 和 Surface
setupSurfaceTexture();
}
注意事项
-
SurfaceTexture
的updateTexImage()
方法必须在每次需要新的图像帧时调用,以确保Surface
上显示的内容是最新的。 -
SurfaceTexture
与 OpenGL ES 的交互需要在 OpenGL ES 的上下文中进行,因此attachToGLContext
和detachFromGLContext
被用来在 OpenGL ES 上下文和SurfaceTexture
之间切换。 -
在
SurfaceTexture
的onFrameAvailable()
回调中,可以执行图像处理或通知渲染线程有新的帧可以渲染。 -
SurfaceTexture
和Surface
的生命周期必须被妥善管理,以避免内存泄漏。 -
使用
SurfaceTexture
可以有效地将图像数据从生产者(如相机)传输到消费者(如 OpenGL ES 或SurfaceView
),同时减少内存复制和上下文切换的开销。
SurfaceTexture
是 Android 中处理实时图像数据的强大工具,适用于需要高效图像处理和显示的应用程序。