欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SurfaceView预览camera

程序员文章站 2022-03-29 18:40:31
...

SurfaceView 预览Camera
实现步骤

1.增加权限
<uses-permission android:name="android.permission.CAMERA"/>
2.动态申请权限
//检查访问摄像头权限
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100);
} else {
    //拥有权限
    initCameraView();
}
3.为SurfaceView的SurfaceHolder增加回调

类中要实现回调 implements SurfaceHolder.Callback

private void initCameraView() {
    surfaceView = findViewById(R.id.surfaceview);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
}
4.Camera相机初始化并关联SurfaceHolder

记得加上这句camera.startPreview()

  @Override
    public void surfaceCreated(final SurfaceHolder holder) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (camera == null)
                        camera = Camera.open(1);
                    camera.setPreviewDisplay(holder);
                    camera.setPreviewCallback(new Camera.PreviewCallback() {
                        @Override
                        public void onPreviewFrame(byte[] data, Camera camera) {
                        }
                    });
                    camera.setDisplayOrientation(90);
                    camera.startPreview();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }