美文网首页
Camera 开发教程一: SurfaceView渲染相机数据

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

作者: 阿怪Sir | 来源:发表于2018-05-10 10:18 被阅读0次

    SurfaceView渲染相机数据

    1. 申请权限

    <uses-permission android:name="android.permission.CAMERA"/>
    

    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文件中引用该控件即可实现相机数据预览

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".moudle.opengl.MainActivity">
    
        <com.aguai.camerademo.moudle.sufaceview.CameraSufaceView
            android:id="@+id/surfaceView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </FrameLayout>
    

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

    相关文章

      网友评论

          本文标题:Camera 开发教程一: SurfaceView渲染相机数据

          本文链接:https://www.haomeiwen.com/subject/zadorftx.html