2017-04-27 31 views
8

我有一个AVCaptureVideoPreviewLayer实例被添加到视图控制器视图层次结构中。当UI旋转被禁用时,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

我已经尝试更新视频层方向如下(无结果):

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

该问题似乎并未与视频层定位本身相关联,但更多的是查看层次结构布局。

UPDATE:

至于建议,我也尝试更新设备上的方向变化,这并没有帮助视频层取向。

我也注意到这个问题大多发生在应用程序启动并且屏幕首次出现之后。在同一会话期间的后续屏幕演示中,问题的再现率非常低(类似1/20)。

+1

注册enterForeground通知,添加FUNC fixOrientation()调用它viewWillAppear中和enterForeground,在方法: UIDevice.current.setValue(NSNumber的(价值:UIInterfaceOrientation。如果它的landscapeLeft/Right,我几年前用Obj-c编写这样的代码,所以写作评论,因为我还没有测试 – SeanLintern88

回答

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; 
} 
+0

谢谢,我尝试过实施你的建议,那也没有帮助。请参阅问题中的更新部分了解更多信息。 – NikGreen

相关问题