美文网首页IOS
iOS中利用CoreMotion获取设备方向

iOS中利用CoreMotion获取设备方向

作者: 黄成 | 来源:发表于2015-05-28 13:35 被阅读2451次

问题:在开发自定义相机的时候,设备如果关闭了设备旋转,那么设备方向获取有一定问题

在使用UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];获取设备方向的时候,如果关闭了设备旋转,那么获取的设备方向都为UIDeviceOrientationPortrait。

iOS5以前可以利用UIAccelerometer进行获取,后面苹果使用CoreMotion替代。

建立一个CMAccelerometerHandler *_motionHandler,

__weak typeof(self) weakSelf = self;

_motionHandler = ^ (CMAccelerometerData *accelerometerData, NSError *error) {

typeof(self) selfBlock = weakSelf;

CGFloat xx = accelerometerData.acceleration.x;

CGFloat yy = -accelerometerData.acceleration.y;

CGFloat zz = accelerometerData.acceleration.z;

CGFloat device_angle = M_PI / 2.0f - atan2(yy, xx);

UIDeviceOrientation orientation = UIDeviceOrientationUnknown;

if (device_angle > M_PI)

device_angle -= 2 * M_PI;

if ((zz < -.60f) || (zz > .60f)) {

if ( UIDeviceOrientationIsLandscape(selfBlock.lastOrientation) )

orientation = selfBlock.lastOrientation;

else

orientation = UIDeviceOrientationUnknown;

} else {

if ( (device_angle > -M_PI_4) && (device_angle < M_PI_4) )

orientation = UIDeviceOrientationPortrait;

else if ((device_angle < -M_PI_4) && (device_angle > -3 * M_PI_4))

orientation = UIDeviceOrientationLandscapeLeft;

else if ((device_angle > M_PI_4) && (device_angle < 3 * M_PI_4))

orientation = UIDeviceOrientationLandscapeRight;

else

orientation = UIDeviceOrientationPortraitUpsideDown;

}

if (orientation != selfBlock.lastOrientation) {

dispatch_async(dispatch_get_main_queue(), ^{

[selfBlock deviceOrientationDidChangeTo:orientation];

});

}

};

使用CMMotionManager *motionManager;开始加速计更新

- (void)startAccelerometerUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMAccelerometerHandler)handler;

最后提一点:

在AVCaptureConnection *videoConnection = [self findVideoConnection];设置方向,图片会自动旋转到portrait

if ([videoConnection isVideoOrientationSupported]) {

switch (self.deviceOrientation) {

case UIDeviceOrientationPortraitUpsideDown:

[videoConnection setVideoOrientation:AVCaptureVideoOrientationPortraitUpsideDown];

break;

case UIDeviceOrientationLandscapeLeft:

[videoConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight];

break;

case UIDeviceOrientationLandscapeRight:

[videoConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeLeft];

break;

default:

[videoConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];

break;

}

}

相关文章

网友评论

  • 皇垚:我现在自定义的录像,想录横屏,但是方向总有问题,能否指点一下,谢谢了
    皇垚:@黄成 就是用AVCaptureSession自定义的相机中,我限定了只能竖屏,但是想在横屏录象的时候,录完的视频是横屏形式,而不是竖屏,该怎么弄呢?您方便加我qq吗?1345490223
    黄成:@皇垚 ?

本文标题:iOS中利用CoreMotion获取设备方向

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