AVCaptureVideoPreviewLayer,视频方向卡住了



我有一个iPhone相机应用程序,我在其中使用AVCaptureVideoPreviewLayer。当有人拍摄照片/静止图像时,这将显示在新的ViewController中。一旦此视图控制器被关闭,魔术就会发生。

整个应用程序正常旋转,两个视图控制器;但有一个例外。如果我在一个方向上拍照,在新的ViewController中旋转设备,然后返回AVCaptureVideoPreviewLayer,整个图层都会很好地旋转,除了图像,所以突然输入通过预览层横向呈现。

我已经检查并尝试为 PreviewLayer 设置框架,但这一切似乎都很好,我在调试时看到的值都是正确的。只是显示的图像是倾斜的。来回旋转设备可在使用过程中解决此问题。

以前有没有人见过这个,有没有人知道如何解决这个问题?

您可以在界面旋转时更改预览图层连接的视频方向

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
self.previewLayer.connection.videoOrientation = self.interfaceOrientation;
}

由于didRotateFromInterfaceOrientation:在iOS 8中已弃用,因此我在viewDidLayoutSubviews中更改了连接的视频方向

switch ([UIApplication sharedApplication].statusBarOrientation) {
case UIInterfaceOrientationPortrait:
self.captureVideoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortrait;
break;
case UIInterfaceOrientationPortraitUpsideDown:
self.captureVideoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
break;
case UIInterfaceOrientationLandscapeLeft:
self.captureVideoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
break;
case UIInterfaceOrientationLandscapeRight:
self.captureVideoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
break;
default:
break;
}

我过去也有类似的问题。 关闭相机控制器后,您可以使用以下内容刷新视图旋转:

UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
UIView *topView = [window.subviews objectAtIndex:0];
[topView removeFromSuperview];
[window addSubview:topView];        

因此,删除显示窗口上的最顶部视图并在窗口上重置它,它应该会正确刷新视图旋转。

希望对你有帮助

也许,与其更改框架AVCaptureVideoPreviewLayer不如尝试将其放入容器UIView中,并设置此容器的框架。(我修复了 UIView 工作this way : sizing directly PreviewLayer had no effect, but sizing its containingÀVCaptureVideoPreviewLayer 上的"大小调整"错误)。

或 也许您可以在视图中强制方向控制器viewWillAppear(或viewDidAppear

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// try and force current orientation
UIApplication *application = [UIApplication sharedApplication];
UIInterfaceOrientation currentOrientation = application.statusBarOrientation;
[application setStatusBarOrientation:currentOrientation animated:animated];
}

祝你好运!

由于 interfaceOriented 已被弃用,最新的 swift 2.0 解决方案应为:

let previewLayerConnection = self.previewLayer.connection
let orientation = AVCaptureVideoOrientation(rawValue: UIApplication.sharedApplication().statusBarOrientation.rawValue)
previewLayerConnection.videoOrientation = orientation!