如何在旋转过程中将`AVCaptureVideoPreviewLayer`剪辑到视图边框

时间:2015-03-27 19:52:23

标签: ios objective-c

我几乎根据Apple关于AVCaptureVideoPreviewLayer的文档添加AVCaptureVideoPreviewLayer,如下所示:

 AVCaptureSession *captureSession = <#Get a capture session#>;<br>
 AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:captureSession];<br>
 UIView *aView = <#The view in which to present the layer#>;<br>
 previewLayer.frame = aView.bounds; // Assume you want the preview layer to fill the view.<br>
 [aView.layer addSublayer:previewLayer];

我添加了didRotateFromInterfaceOrientation函数,以便使用以下代码处理轮换:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
    [self.videoPreviewLayer setFrame:self.view.layer.bounds];
    [self.videoPreviewLayer.connection setVideoOrientation:[self getAVCaptureVideoOrientation]];
}

- (AVCaptureVideoOrientation)getAVCaptureVideoOrientation {
    UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];
    if ( deviceOrientation == UIDeviceOrientationLandscapeLeft )
        return AVCaptureVideoOrientationLandscapeRight;
    else if 
        // and other 3 orientations
        // ...
}

结果看起来不错,但动画不太好。相机层不会开始调整大小直到旋转完成,我可以在旋转期间看到背景视图。

http://yzhong.co/wp-content/uploads/2015/03/My_Movie_1_-_Small.gif

然后我开始环顾四周,找到了这两个问题:Problems automatically resizing AVCaptureVideoPreviewLayer on rotationAVCaptureVideoPreviewLayer smooth orientation rotation。我尝试了那些问题中提出的解决方案并添加了以下功能:

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    if (_videoPreviewLayer) {
        if (toInterfaceOrientation==UIInterfaceOrientationPortrait) {
            [self.videoPreviewLayer setAffineTransform:CGAffineTransformMakeRotation(0)];
        } else if (toInterfaceOrientation==UIInterfaceOrientationLandscapeLeft) {
            [self.videoPreviewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI/2)];
        } else if (toInterfaceOrientation==UIInterfaceOrientationLandscapeRight) {
            [self.videoPreviewLayer setAffineTransform:CGAffineTransformMakeRotation(-M_PI/2)];
        } else {
            [self.videoPreviewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI)];
        }
        self.videoPreviewLayer.frame = self.view.bounds;
    }
}

我得到以下内容,这要好得多。然而,动画仍然有点奇怪。好像它向后旋转然后向前移动到正确的位置?现在我不知道接下来要做什么。

http://yzhong.co/wp-content/uploads/2015/03/My_Movie_2_-_Small.gif

我正在寻找的非常简单。我希望有一个漂亮,流畅和自然的过渡/旋转,例如Apple的默认相机应用程序。谁能告诉我这里做错了什么?

http://yzhong.co/wp-content/uploads/2015/03/My_Movie_3_-_Small.gif

请帮忙!

0 个答案:

没有答案