我已经实现了下面的代码来更改方向AVCaptureVideoSession
基于UIInterfaceOrientation
:
- (AVCaptureVideoOrientation)interfaceOrientationToVideoOrientation:(UIInterfaceOrientation)orientation {
switch (orientation) {
case UIInterfaceOrientationPortrait:
return AVCaptureVideoOrientationPortrait;
case UIInterfaceOrientationPortraitUpsideDown:
return AVCaptureVideoOrientationPortraitUpsideDown;
case UIInterfaceOrientationLandscapeLeft:
return AVCaptureVideoOrientationLandscapeLeft;
case UIInterfaceOrientationLandscapeRight:
return AVCaptureVideoOrientationLandscapeRight;
default:
break;
}
NSLog(@"Warning - Didn't recognise interface orientation (%ld)",(long)orientation);
return AVCaptureVideoOrientationPortrait;
}
这段代码几乎可以完美运行。然而,出现的一个问题是,如果您快速旋转 iOS 设备 180 度,相机将显示颠倒。
这是旋转之前相机视图的样子:
这是旋转后的样子:
另外,这是我的实现viewDidLayoutSubviews
:
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
previewLayer.frame = self.view.bounds;
self.view.translatesAutoresizingMaskIntoConstraints = NO;
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:previewLayer];
if (previewLayer.connection.supportsVideoOrientation) {
previewLayer.connection.videoOrientation = [self interfaceOrientationToVideoOrientation:[UIApplication sharedApplication].statusBarOrientation];
}
}
有谁知道为什么发生 180 度旋转时相机视图会颠倒?
我相信它正在发生,因为viewDidLayoutSubviews
当视图从纵向更改为颠倒时,不会调用。当你旋转得非常快时,它会从一个直线转到另一个直线。如果你缓慢旋转,它会穿过横向方向,所以viewDidLayoutSubviews
被调用,随后是你的方法。
我建议您使用方向改变时调用的方法之一。我知道苹果公司建议越来越少地使用它们,因为他们希望视图在尺寸变化时也随之变化,但也有一些情况,比如这个,你确实需要知道方向发生了变化。
例如,您可以注册以接收此通知:
UIApplicationDidChangeStatusBarOrientationNotification
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)