如果要将Camera与TextureSurface一起使用,可以实现SurfaceTextureListener接口。你必须实现4种方法:
1)onSurfaceTextureAvailable – 在这里设置你的相机
2)onSurfaceTextureSizeChanged – 在你的情况下,Android的相机将处理这个方法
3)onSurfaceTextureDestroyed – 在这里你销毁所有相机的东西。
4)onSurfaceTextureUpdated-当你有改变的东西时,在这里更新你的纹理!
请查看以下示例:
public class MainActivity extends Activity implements SurfaceTextureListener{
private Camera mCamera;
private TextureView mTextureView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextureView = new TextureView(this);
mTextureView.setSurfaceTextureListener(this);
setContentView(mTextureView);
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
mCamera = Camera.open();
Camera.Size previewSize = mCamera.getParameters().getPreviewSize();
mTextureView.setLayoutParams(new FrameLayout.LayoutParams(
previewSize.width, previewSize.height, Gravity.CENTER));
try {
mCamera.setPreviewTexture(surface);
} catch (IOException t) {
}
mCamera.startPreview();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
// Ignored, the Camera does all the work for us
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
mCamera.stopPreview();
mCamera.release();
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
// Update your view here!
}
}
还有两件事:不要忘记在项目的清单中添加摄像头权限,并且可以从API 11获得SurfaceTexture。