美文网首页iOS 知识收集
iOS-使用传感器监听设备的物理方向(横向纵向)

iOS-使用传感器监听设备的物理方向(横向纵向)

作者: Zafir_zzf | 来源:发表于2017-07-19 17:58 被阅读34次

    在自定义视频录制界面的时候,我们需要在用户开始录制之前确定将要拍摄视频的方向(竖直还是水平),如果用户横过来拍摄结果播放出来还是竖直让用户歪着头看那就尴尬了。

    歪着的视频

    控制录制视频是横向还是竖直的是AVCaptureMovieFileOutput中的**AVCaptureConnection的videoOrientation... **


    视频的四个方向.png

    在开始录制之前我们就要确认了这个参数,一般情况下我们会分竖直Portrait和侧过来的Left。所以如何判断用户是竖着拍还是横着拍的呢?

    UIViewController有一个监听方法
    - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
    不管用,这个方法只有开启了屏幕旋转,屏幕真正旋转的时候才会调用。

    UIDevice也有监听屏幕旋转的方法UIDeviceOrientationDidChangeNotification
    然而这两个方法的使用场景很有限,设备开了竖排锁定它们是不知道设备转了向的

    这个场景只有使用强大的传感器中的加速计才管用。
    #import <CoreMotion/CoreMotion.h>
    @property (nonatomic, strong) CMMotionManager *mManager;
    我写了一个CMMotionManager的一个分类,用来抽取这个判断设备方向的方法。

    
      #import "CMMotionManager_Extension.h"
    
      @implementation CMMotionManager (_Extension)
    
    - (void)startUpdateAccelerometerResult:(void(^)(NSInteger))result {
        NSTimeInterval  updateInterval = 1.0/15.0; //几秒监测一次
        if ([self isAccelerometerAvailable] == YES) {
            [self setAccelerometerUpdateInterval: updateInterval];
            [self startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
                CMAcceleration acceleration =  accelerometerData.acceleration;
                if (acceleration.x >= 0.75) {
                    //left
                }
                else if (acceleration.x <= -0.75) {
                   //right
                }
                else if (acceleration.y <= -0.75) {
                    //Portriat
                }
                else if (acceleration.y >= 0.75) {
                   //UpsideDown
                }
                else {
                    // Consider same as last time
                    return;
                }
            }];
        }
    }
    - (void)stopUpdate {
        if ([self isAccelerometerActive] == YES) {
            [self stopAccelerometerUpdates];
        }
    }
    

    调用了 startAccelerometerUpdatesToQueue后,block会根据设置的updateInterval一直进行回调所监测的方向。像微信APP的录制视频界面会在用户横着录像的时候界面也发生一些变化来提示用户当前是在横着录,那就需要一直监测。你也可以在用户点击了录制按钮时开启这个方法,在block中再设置方向,开始录制,要记得stopUpdate。

    相关文章

      网友评论

        本文标题:iOS-使用传感器监听设备的物理方向(横向纵向)

        本文链接:https://www.haomeiwen.com/subject/tlzlkxtx.html