禁用UI旋转时AVCaptureVideoPreviewLayer方向错误

时间:2017-04-27 13:12:26

标签: ios objective-c rotation avfoundation avcapturesession

我在视图控制器视图层次结构中添加了AVCaptureVideoPreviewLayer实例。

- (void) loadView {
   ...

   self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:nil];
   self.previewLayer.frame = self.view.bounds;
   self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

   [self.view.layer addSublayer: _previewLayer];

   // adding other UI elements
   ...
}

...

- (void) _setupPreviewLayerWithSession: (AVCaptureSession*) captureSession
{
   self.previewLayer.session = self.captureManager.captureSession;
   self.previewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
}

图层框架在-viewDidLayoutSubviews方法中更新。视图控制器方向锁定为UIInterfaceOrientationMaskLandscapeRight

问题如下:

  1. 设备以横向方式保持
  2. 视图控制器以模态方式显示 - 视频图层正确显示。 Correct orientation
  3. 然后锁定设备,当设备锁定时,设备将旋转为纵向。
  4. 然后在仍然处于纵向的情况下解锁设备,并在几秒钟内将视频图层旋转90度显示。但是,视频层的帧是正确的。所有其他UI元素都正确显示。几秒钟后,图层会捕捉到正确的方向。 请在下面找到图层和UI元素的边界 Incorrect orientation
  5. 我尝试将视频图层方向更新为以下内容(没有结果):

    • 订阅AVCaptureSessionDidStartRunningNotificationUIApplicationDidBecomeActiveNotification次通知
    • 在调用-viewWillTransitionToSize:withTransitionCoordinator:方法时调用更新
    • on -viewWillAppear:

    问题似乎与视频图层方向本身无关,而是与查看层次结构布局有关。

    更新

    正如所建议的那样,我也尝试更新设备方向更改的视频图层方向,但没有帮助。

    我还注意到问题主要发生在启动应用程序并首次显示屏幕之后。在同一会话期间的后续屏幕演示中,问题的重现率非常低(例如1/20)。

1 个答案:

答案 0 :(得分:3)

试试这段代码:

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(orientationChanged:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil];
-(void)orientationChanged:(NSNotification *)notif {

    [_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    if (_videoPreviewLayer.connection.supportsVideoOrientation) {
        _videoPreviewLayer.connection.videoOrientation = [self interfaceOrientationToVideoOrientation:[UIApplication sharedApplication].statusBarOrientation];
    }

}

- (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 (%d)",orientation);
    return AVCaptureVideoOrientationPortrait;
}