在Android中使用SurfaceTexture进行相机预览的示例 [英] Example of Camera preview using SurfaceTexture in Android
问题描述
我正在尝试使用 SurfaceTexture 渲染摄像机预览.我阅读了该文档,但无法理解其工作原理.
I am trying to render camera preview using SurfaceTexture. I read the document but unable to understand how it works.
任何人都可以提供一个示例示例(非常基本的示例)或使用 SurfaceTexture 进行链接的示例预览相机.我用谷歌搜索了一下,但没有找到我想要的东西.
Can anyone provide one sample example(very basic one) or link which uses SurfaceTexture to preview camera. I googled this but not found what I am looking for.
谢谢.
推荐答案
如果您想将Camera与TextureSurface一起使用,则可以实现SurfaceTextureListener
接口.您将必须实现4种方法:
If you want to use the Camera with TextureSurface you can implement SurfaceTextureListener
interface. You'll have to implement 4 methods:
1)onSurfaceTextureAvailable
-在这里设置相机
1) onSurfaceTextureAvailable
- Here you setup your camera
2)onSurfaceTextureSizeChanged
-在您的情况下,Android的相机将处理此方法
2)onSurfaceTextureSizeChanged
- In your case, the Android's camera will handle this method
3)onSurfaceTextureDestroyed
-在这里您销毁了所有相机东西.
3)onSurfaceTextureDestroyed
- Here you destroy all camera stuff.
4)onSurfaceTextureUpdated
-如果要更改某些内容,请在此处更新您的纹理!
4) onSurfaceTextureUpdated
- Update your texture here when you have something to change!
检查以下示例:
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!
}
}
还有两件事:不要忘记在项目清单中添加摄像机权限,并且SurfaceTexture
可从API 11获得.
Two more things: Don't forget to add the camera permissions in your project's manifest and the SurfaceTexture
is available from API 11.
这篇关于在Android中使用SurfaceTexture进行相机预览的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!