Camera 开发教程一: SurfaceView渲染相机数据

SurfaceView渲染相机数据

1. 申请权限


2.自定义surfaceView

public class CameraSufaceView extends SurfaceView implements SurfaceHolder.Callback {
private Camera mCamera;

public CameraSufaceView(Context context) {
    super(context);
    init();
}


public CameraSufaceView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();

}
public CameraSufaceView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}
private void init() {
    getHolder().addCallback(this);
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    L.i("surfaceCreated...");
    if (mCamera == null) {
        mCamera = Camera.open();//开启相机
        try {
            mCamera.setDisplayOrientation(90);
            mCamera.setPreviewDisplay(holder);//相机预览的内容放在 holder
        } catch (IOException e) {
            ToastUtils.showShort(" 设置预览失败");
            e.printStackTrace();
        }
    }
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    L.i( "surfaceChanged...");
    try {
        mCamera.stopPreview();
    }catch (Exception e){
        e.printStackTrace();
    }
    mCamera.startPreview();//该方法只有相机开启后才能调用
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    L.i( "surfaceDestroyed...");
    if (mCamera != null) {
        mCamera.lock();
        mCamera.stopPreview();
        mCamera.release();//释放相机资源
        mCamera = null;
    }
}

}

3. 在xml文件中引用该控件即可实现相机数据预览



    


4. 项目地址:https://github.com/aguai1/CameraDemo 定时更新

你可能感兴趣的:(Camera 开发教程一: SurfaceView渲染相机数据)