从零开发一款相机APP 第七篇: Camera2相机 预览功能实现

2022-12-20 19:16:10 浏览数 (3)

代码语言:javascript复制
本课程内容由 @公众号:小驰笔记出品,欢迎关注公众号,获取更多交流信息~
显示需要借助surface,一般采用surfaceview或者textureview;
相关重要流程:

1、自定义TextureView

代码语言:javascript复制
private AutoFitTextureView mTextureView;

2、Activity OnResume的时候,判断mTextureView 当前状态。如果是available状态,则直接打开camera,否则设置surfaceTexture监听

代码语言:javascript复制
if (mTextureView.isAvailable()) {
            openCamera(mTextureView.getWidth(), mTextureView.getHeight());
 } else {
            mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
 }

3、surfaceTexture监听中,SurfaceTextureAvailable的时候,去执行opencamera的操作

代码语言:javascript复制
private final TextureView.SurfaceTextureListener mSurfaceTextureListener
            = new TextureView.SurfaceTextureListener() {

        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
            openCamera( width, height);
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {
            configureTransform(width, height);
        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
            return true;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture texture) {
        }
    };

4、设置surface target

代码语言:javascript复制
Surface surface = new Surface(texture);
// We set up a CaptureRequest.Builder with the output Surface.
mPreviewRequestBuilder
		= mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(surface);

5、 创建会话中,传入surface

代码语言:javascript复制
mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {
}

深圳上班,

从事Android Camera相关软件开发工作,

公众号记录生活和工作的点滴,

0 人点赞