问题:在开发自定义相机的时候,设备如果关闭了设备旋转,那么设备方向获取有一定问题
在使用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;
}
}