Rotating a Camera SurfaceView to portrait

前端 未结 7 1004
日久生厌
日久生厌 2020-12-14 04:37

I have looked up a few posts on changing the orientation of the camera with a surface view, but I have taken my code from the examples at:

http://developer.android.c

7条回答
  •  离开以前
    2020-12-14 04:55

    Well i Do this!

    I have solved this issue in in this way in surfaceCreated() method

     public void surfaceCreated(SurfaceHolder holder) {
        try {
    
            camera = Camera.open();
        } catch (RuntimeException e) {
            System.err.println(e);
            return;
        }
        Camera.Parameters param;
        param = camera.getParameters();
        if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE)
        {
            param.set("orientation", "portrait");
            setCameraDisplayOrientation(this,1,camera);
        }
        camera.setParameters(param);
    
        try {
            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();
        } catch (Exception e) {
            System.err.println(e);
            return;
        }
    }
    

    add this method below

     public static void setCameraDisplayOrientation(Activity activity,
                                                   int cameraId, android.hardware.Camera camera) {
    
        android.hardware.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);
    }
    

    3: Make sure you have added camera permiison to support for nougat in a activity before this activity calling dont call permission for camera in this activity because surfacecreated call as the activity created, and your permission will be pending to open camera

提交回复
热议问题