【问题标题】:What's the correct way to detect a screen rotation from 0 to 180, or 90 to 270?检测屏幕旋转从 0 到 180 或 90 到 270 的正确方法是什么?
【发布时间】:2013-12-12 11:51:01
【问题描述】:

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

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

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

检测这种变化的最佳方法是什么,以便我可以适当地重新定位我的相机预览?

【问题讨论】:

    标签: android rotation orientation


    【解决方案1】:

    使用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

    【讨论】:

      猜你喜欢
      • 2013-08-19
      • 2013-04-22
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      相关资源
      最近更新 更多