检测屏幕旋转的正确方法是0到180,或90到270?

时间:2013-12-12 11:51:01

标签: android rotation orientation

我正在尝试根据屏幕的旋转来定位相机预览。

我注意到,当在具有匹配尺寸的方向之间直接旋转(因此,0 - > 180和90 - > 270)时,配置不会更改,并且活动不会重新启动。

我目前在Display.getRotation()内使用Activity.onCreate(),但此信息已过期。

检测此更改的最佳方法是什么,以便我可以适当地重新定位相机预览?

1 个答案:

答案 0 :(得分:3)

使用OrientationEventListener

在SurfaceHolder.Callback

    orientationListener = createOrientationListener();

    private OrientationEventListener createOrientationListener() {
            return new OrientationEventListener(getActivity()) {
                public void onOrientationChanged(int orientation) {
                    try {
                        if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
                            setCameraDisplayOrientation(getActivity().getWindowManager().getDefaultDisplay().getRotation());
                        }
                    } catch (Exception e) {
                        Log.w(TAG, "Error while onOrientationChanged", e);
                    }
                }
            };
        }


     @Override
     public void surfaceCreated(SurfaceHolder holder) {
         orientationListener.enable();
     }


    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        orientationListener.disable();
    }

您的更改轮换方法必须管理不需要的双重旋转

public void setCameraDisplayOrientation(int displayRotation) {
            int degrees = 0;
            switch (displayRotation) {
                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 (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                result = (cameraInfo.orientation + degrees) % 360;
                result = (360 - result) % 360;  // compensate the mirror
            } else {  // back-facing
                result = (cameraInfo.orientation - degrees + 360) % 360;
            }
            if(result != currentSetRotation) {
                    currentSetRotation = result;
                    camera.setDisplayOrientation(result);
                    Log.d(TAG,"For displayRotation "+displayRotation+" we set a camera rotation of "+result);

            }
    }

另请参阅:Rotating phone quickly 180 degrees, camera preview turns upside down