在竖屏锁定下,判断屏幕方向的问题

自定义相机拍照和录制的时候,需求是横屏录制或拍照的时候,预览视频或图片要求竖屏显示。首先想到添加屏幕旋转通知,控制视屏或图片输入源方向。

添加屏幕旋转的通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleDeviceOrientationChange:) name:UIDeviceOrientationDidChangeNotification object:nil];

但是当用户把竖屏锁定开启的时候,是无法接受到通知的,系统默认屏幕一直是竖屏状态。
这个时候就需要用到陀螺仪和加速器来判断屏幕的横竖屏状态。
首先引入CoreMotion.frameWork框架

    @property (nonatomic, strong) CMMotionManager * motionManager;

    - (void)startMotionManager{
          if (_motionManager == nil) {
                _motionManager = [[CMMotionManager alloc] init];
          }
           _motionManager.deviceMotionUpdateInterval = 1/15.0; // 每隔一个时间做一次轮询
          if (_motionManager.deviceMotionAvailable) {
                LRWeakSelf(self)
              [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
                                         withHandler: ^(CMDeviceMotion *motion, NSError *error){
                                             [weakself performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];

                                         }];
          } else {
               [self setMotionManager:nil];
          }
    }

    - (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion{
        double x = deviceMotion.gravity.x;
        double y = deviceMotion.gravity.y;
        AVCaptureVideoOrientation deviceOrientation;
        if (fabs(y) >= fabs(x))
        {
            if (y >= 0){
                // UIDeviceOrientationPortraitUpsideDown;  屏幕方向
                deviceOrientation = AVCaptureVideoOrientationPortraitUpsideDown; // 设置视频或图片的输入源的方向
           }else{
                  // UIDeviceOrientationPortrait;
                deviceOrientation = AVCaptureVideoOrientationPortrait;
            }
        }else{
            if (x >= 0){
                // UIDeviceOrientationLandscapeRight;
                deviceOrientation = AVCaptureVideoOrientationLandscapeLeft;
            }else{
                // UIDeviceOrientationLandscapeLeft;
                deviceOrientation = AVCaptureVideoOrientationLandscapeRight;
            }
        }
        self.deviceOrientation = deviceOrientation;
    }

当点击拍摄或录像的时候,设置下输入源的方向,控制视频或图片的方向。

结束的时候调用
[_motionManager stopDeviceMotionUpdates];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言:今天项目中度打算添加直播推流的功能,其中有一个需求,感觉没啥用处,但是产品又必须要添加的功能,就是要在打开推...
    MTSu1e丶阅读 587评论 0 1
  • 在开发中,有时候我们需要让某些特定的页面为横屏展示,而从这个页面离开或者进入其他页面时为竖屏,起初我仅仅依赖了UI...
    MTDeveloper阅读 5,829评论 0 2
  • 昨日,跟一个朋友出去吃饭的时候谈到了“伤害”这个话题。夜里思来想去总觉得我们每一个人,都处在一个伤害与被伤害,误解...
    我是发儿呀阅读 1,231评论 2 6
  • 一曲悠悠悲弥天,岸边飞雪飘入帘。 敢问宽仁天九重,此地愤然何处平。 高地长街千万里,独有吾家风满屋, 再问大善佛菩...
    琪菇晾阅读 331评论 4 2
  • 傅红雪 白落原 林资阳 叶橘林 沈染 ①别人眼中的洒脱 “你不后悔吗,驰骋他真的不错。”两个女孩在夕...
    real_SSSyy阅读 539评论 0 0