Android Camera + SurfaceView 实现相机预览

    <uses-permission android:name="android.permission.RECORD_AUDIO"/><!--音频录制权限-->
    <uses-permission android:name="android.permission.CAMERA"/><!--摄像头权限-->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><!--存储权限-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">

    <SurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
public class MainActivity extends AppCompatActivity {
    private Camera mCamera;
    private boolean isPreview = false;
    private SurfaceView mSurfaceView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        mTextureView = new TextureView(this);
//        mTextureView.setSurfaceTextureListener(MainActivity.this);
//        mTextureView.setScaleX(-1f);
//        setContentView(mTextureView);
        mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        mSurfaceView.getLayoutParams().width=480;
        mSurfaceView.getLayoutParams().height=640;


        // 获得 SurfaceHolder 对象
        SurfaceHolder mSurfaceHolder = mSurfaceView.getHolder();

        // 设置 Surface 格式
        // 参数: PixelFormat中定义的 int 值 ,详细参见 PixelFormat.java
        mSurfaceHolder.setFormat(PixelFormat.TRANSPARENT);

//        Matrix matrix = new Matrix();
//        matrix.postRotate(90);
        ///mSurfaceView.setTransform(matrix);


        // 如果需要,保持屏幕常亮
        // mSurfaceHolder.setKeepScreenOn(true);

        // 设置 Surface 的分辨率
        // mSurfaceHolder.setFixedSize(width,height);

        // 添加 Surface 的 callback 接口
        mSurfaceHolder.addCallback(mSurfaceCallback);
    }
    private SurfaceHolder.Callback mSurfaceCallback = new SurfaceHolder.Callback() {

        /**
         *  在 Surface 首次创建时被立即调用:活得叫焦点时。一般在这里开启画图的线程
         * @param surfaceHolder 持有当前 Surface 的 SurfaceHolder 对象
         */
        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            try {
                //打开硬件摄像头 这两句默认是后摄像头,如果指定摄像头用 : Camera.open(CameraId) CameraId  0 (后置)  1 (前置)
                // Camera.open() 默认返回的后置摄像头信息 //导包得时候一定要注意是android.hardware.Camera
                // setCameraDisplayOrientation(MainActivity2.this,0,camera);

                //设置角度,此处 CameraId  0 (后置)  1 (前置)
                    mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);//打开硬件摄像头,这里导包得时候一定要注意是android.hardware.Camera
                    setCameraDisplayOrientation(MainActivity.this,0,mCamera);


                //此处也可以设置摄像头参数
                /**
                 WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);//得到窗口管理器
                 Display display  = wm.getDefaultDisplay();//得到当前屏幕
                 Camera.Parameters parameters = camera.getParameters();//得到摄像头的参数
                 parameters.setPictureFormat(PixelFormat.RGB_888);//设置照片的格式
                 parameters.setJpegQuality(85);//设置照片的质量
                 parameters.setPictureSize(display.getHeight(), display.getWidth());//设置照片的大小,默认是和     屏幕一样大
                 camera.setParameters(parameters);//设置需要预览的尺寸
                 **/
                //mSurfaceView.setScaleY(1);
                mCamera.setPreviewDisplay(surfaceHolder);//通过SurfaceView显示取景画面
                mCamera.startPreview();//开始预览
                isPreview = true;//设置是否预览参数为真
            } catch (IOException e) {
                Log.e("TAG", e.toString());
            }
        }

        /**
         *  在 Surface 格式 和 大小发生变化时会立即调用,可以在这个方法中更新 Surface
         * @param surfaceHolder   持有当前 Surface 的 SurfaceHolder 对象
         * @param format          surface 的新格式
         * @param width           surface 的新宽度
         * @param height          surface 的新高度
         */
        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
        }

        /**
         *  在 Surface 被销毁时立即调用:失去焦点时。一般在这里将画图的线程停止销毁
         * @param surfaceHolder 持有当前 Surface 的 SurfaceHolder 对象
         */
        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            if(mCamera != null){
                if(isPreview){//正在预览
                    mCamera.stopPreview();
                    mCamera.release();
                }
            }
        }
    };

    /**
     * 设置 摄像头的角度
     *
     * @param activity 上下文
     * @param cameraId 摄像头ID(假如手机有N个摄像头,cameraId 的值 就是 0 ~ N-1)
     * @param camera   摄像头对象
     */
    public static void setCameraDisplayOrientation(Activity activity,
                                                   int cameraId, android.hardware.Camera camera) {

        Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
        //获取摄像头信息
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();

        //获取摄像头当前的角度
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            //前置摄像头
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360; // compensate the mirror
        } else {
            // back-facing  后置摄像头
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,我会给您讲解使用 SurfaceTexture 和 SurfaceView 实现相机预览的方法。 首先,在布局文件中添加一个 SurfaceView: ```xml <SurfaceView android:id="@+id/surfaceView" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` 然后在 Activity 或 Fragment 中获取 SurfaceView,并设置相机预览: ```java // 获取 SurfaceView SurfaceView surfaceView = findViewById(R.id.surfaceView); // 获取相机实例 Camera camera = Camera.open(); try { // 设置相机预览显示的 Surface camera.setPreviewDisplay(surfaceView.getHolder()); // 开始预览 camera.startPreview(); } catch (IOException e) { e.printStackTrace(); } ``` 接下来,我们来使用 SurfaceTexture 来实现相机预览。 首先,在布局文件中添加一个 TextureView: ```xml <TextureView android:id="@+id/textureView" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` 然后在 Activity 或 Fragment 中获取 TextureView,并设置相机预览: ```java // 获取 TextureView TextureView textureView = findViewById(R.id.textureView); // 获取相机实例 Camera camera = Camera.open(); try { // 创建 SurfaceTexture SurfaceTexture surfaceTexture = new SurfaceTexture(0); // 设置相机预览显示的 Surface camera.setPreviewTexture(surfaceTexture); // 开始预览 camera.startPreview(); } catch (IOException e) { e.printStackTrace(); } ``` 使用 SurfaceTexture 来实现相机预览的好处在于,可以通过 TextureView 的 setSurfaceTextureListener() 方法来监听 SurfaceTexture 的状态,例如当 SurfaceTexture 准备好后,可以获取它的宽高等信息,从而进行一些额外的操作。 希望这些代码可以帮助到您。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王睿丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值