在 flutter 中手机和平板电脑上一致的相机预览旋转行为

Consistent camera preview rotation behavior on phones and tablets in flutter

我正在努力让我的应用程序在移动设备和平板电脑上保持一致。我的目标是让相机预览与设备一起旋转。从 this question 上的答案开始,我创建了自动旋转相机预览以与屏幕对齐的代码:

 NativeDeviceOrientationReader(builder: (context) {
            NativeDeviceOrientation orientation =
                NativeDeviceOrientationReader.orientation(context);
            // Works well for phones.
            int turns;
            switch (orientation) {
              case NativeDeviceOrientation.landscapeLeft:
                turns = 3;
                break;
              case NativeDeviceOrientation.landscapeRight:
                turns = 1;
                break;
              case NativeDeviceOrientation.portraitDown:
                turns = 2;
                break;
              default:
                turns = 0;
                break;
            }
            return RotatedBox(
              quarterTurns: turns,
              child: AspectRatio(
                aspectRatio: controller.value.aspectRatio,
                child: CameraPreview(controller),
              ),
            );
          }),

这适用于 "natively" 处于纵向模式(屏幕和摄像头)的手机。但是,对于我的平板电脑(Pixel C,如果重要的话),在横向模式下 "natively",我必须以不同的方式设置旋转行为:

            // This works on a tablet, but not on a phone.
            switch (orientation) {
              case NativeDeviceOrientation.landscapeLeft:
                turns = 0;
                break;
              case NativeDeviceOrientation.landscapeRight:
                turns = 2;
                break;
              case NativeDeviceOrientation.portraitDown:
                turns = 1;
                break;
              default:
                turns = 3;
                break;
            }
        ...
        // Then also later:
        //  aspectRatio: 1 / controller.value.aspectRatio,

有没有办法

请注意,我知道仅设置首选方向的替代解决方案:

SystemChrome.setPreferredOrientations([
  DeviceOrientation.portraitUp,
]);

这不适合我的应用程序,因为除了相机预览之外,我还有其他内容需要随方向一起旋转。

我通过读取相机控制器的 sensorOrientation 找到了解决方案。 phone 报告 90,而平板电脑报告 0。将相机预览包裹在旋转框中,根据读数设置旋转,解决了这个问题。

    RotatedBox(
      quarterTurns: 1 - controller.description.sensorOrientation ~/ 90,
      child: CameraPreview(controller),
    );