AVCaptureSession相机固定方向,带旋转接口

时间:2015-03-17 18:41:28

标签: ios avcapturesession

假设通常的A等摄像头实现,使用AVCaptureVideoPreviewLayer进行预览。现在在控件(和约束)的顶部添加另一个视图。现在,当手机旋转时,控件以典型方式旋转,但我希望预览不变,就像Apple的相机应用程序一样。如何使预览与控件一起旋转?

这很有效,但动画很难看:

 - (void) deviceOrientationDidChange
 {
     UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

     if (orientation == UIDeviceOrientationFaceUp || orientation == UIDeviceOrientationFaceDown || orientation == UIDeviceOrientationUnknown || currentOrientation == orientation)
     {
         return;
     }

     currentOrientation = orientation;

     if (self.previewLayer)
     {
         if (orientation == UIInterfaceOrientationPortrait)
         {
             self.previewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortrait;
             self.previewLayer.frame = self.view.bounds;
         }
         else if (orientation == UIInterfaceOrientationLandscapeLeft)
         {
             self.previewLayer.frame = self.view.bounds;
             self.previewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;
         }
         else if (orientation == UIInterfaceOrientationLandscapeRight)
         {
             self.previewLayer.frame = self.view.bounds;
             self.previewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight;
         }
     }
 }

1 个答案:

答案 0 :(得分:0)

- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    _lowerWindow = [[UIWindow alloc]initWithFrame:self.window.bounds];
    _lowerWindow.backgroundColor = [UIColor clearColor];
    _lowerWindow.hidden = NO;
    return YES;
}

然后在您创建预览时

[self setPreviewLayer:[[AVCaptureVideoPreviewLayer alloc] initWithSession:captureSession]];

[self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

CGRect layerRect = [[[self view] layer] bounds];
[self.previewLayer setBounds:layerRect];
[self.previewLayer setPosition:CGPointMake(CGRectGetMidX(layerRect),
                                           CGRectGetMidY(layerRect))];

self.cameraView = [[UIView alloc]initWithFrame:[self.view bounds]];
[[self.cameraView layer] addSublayer:self.previewLayer];

AppDelegate* delegate = [[UIApplication sharedApplication] delegate];
[delegate.lowerWindow insertSubview:self.cameraView belowSubview:self.view];

这使用第二个UIWindow,它将包含预览图层;由故事板创建的原始UIWindow包含UI并旋转,而这个不旋转。唯一的缺点是旋转过程中屏幕变成空白。

仅在iOS 8上测试过。