用户锁定屏幕旋转时,如何以编程方式知道设备方向

时间:2016-05-23 07:33:49

标签: ios camera avfoundation orientation

在我的相机项目中,我想知道用户(如系统相机)锁定屏幕旋转时的设备方向。

我如何知道设备方向或仅为我的项目解锁屏幕旋转?

3 个答案:

答案 0 :(得分:0)

您可以找到几种方法来获取当前设备方向或方向更改here

答案 1 :(得分:0)

您可以使用CoreMotion。 查看此库here

答案 2 :(得分:0)

感谢Xcoder,coreMotion帮助了我。

按照我的代码:

- (void)startMotionManager{
    if (_motionManager == nil) {
        _motionManager = [[CMMotionManager alloc] init];
    }
    _motionManager.deviceMotionUpdateInterval = 1/2.0;
    if (_motionManager.deviceMotionAvailable) {
        NSLog(@"Device Motion Available");
        [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
                                            withHandler: ^(CMDeviceMotion *motion, NSError *error){
            [self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];
        }];
    } else {
        NSLog(@"No device motion on device.");
        [self setMotionManager:nil];
    }
}

- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion {
    double x = deviceMotion.gravity.x;
    double y = deviceMotion.gravity.y;
    if (fabs(y) >= fabs(x)) {
        if (y >= 0) {
            self.deviceOrientation = UIDeviceOrientationPortraitUpsideDown;
        } else {
            self.deviceOrientation = AVCaptureVideoOrientationPortrait;
        }
    } else {
        if (x >= 0) {
            self.deviceOrientation = UIDeviceOrientationLandscapeRight;
        }
        else {
            self.deviceOrientation = UIDeviceOrientationLandscapeLeft;
        }
    }
}