iOS:相机方向问题

12

我想使用AVCaptureSession从相机拍摄一张图片。

它可以正常工作,我启动了相机并可以得到输出。然而,在旋转设备时,视频方向存在一些问题。

首先,我想支持左右横屏和可能后续的竖屏模式。

我实现了:

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation{ 
return UIInterfaceOrientationIsLandscapse(interfaceOrientation);
}

当我旋转设备时,它将应用程序从左侧横向旋转到右侧横向或者相反,但只有当我处于左侧横向时才可以正确地查看相机。当应用程序处于右侧横向时,视频会旋转180度。

非常感谢。

更新:

我尝试了Spectravideo328的答案,但当我尝试旋转设备时出现错误并且应用程序崩溃。这是错误:

[AVCaptureVideoPreviewLayer connection]: unrecognized selector sent to instance 0xf678210

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AVCaptureVideoPreviewLayer connection]: unrecognized selector sent to instance 0xf678210'

错误发生在这一行:

AVCaptureConnection *previewLayerConnection=self.previewLayer.connection;
我将其放在 shouldAutorotateToInterfaceOrientation 方法中。你知道这个错误的原因吗?
谢谢。
1个回答

24

默认相机方向是 UIInterfaceOrientationLeft,有些奇怪。

设备旋转时,相机方向不会随之改变,它们是独立的。您需要手动调整相机方向:

将以下内容放入一个方法中,将该方法传递给 toInterfaceOrientation(也许您可以在上面的 shouldAutorotateToInterfaceOrientation 中调用它,以便设备旋转和相机旋转):

首先,您必须获取预览层连接。

AVCaptureConnection *previewLayerConnection=self.previewLayer.connection;

if ([previewLayerConnection isVideoOrientationSupported])
{
    switch (toInterfaceOrientation)
    {
        case UIInterfaceOrientationPortrait:
            [previewLayerConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];
            break;
        case UIInterfaceOrientationLandscapeRight:
            [previewLayerConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight]; //home button on right. Refer to .h not doc
            break;
        case UIInterfaceOrientationLandscapeLeft:
            [previewLayerConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeLeft]; //home button on left. Refer to .h not doc
            break;
        default:
            [previewLayerConnection setVideoOrientation:AVCaptureVideoOrientationPortrait]; //for portrait upside down. Refer to .h not doc
            break;
    }
}

这个解决方案对我不起作用。它什么也没做... 我使用 [self.prevLayer setOrientation:[[UIDevice currentDevice] orientation]] 解决了问题。但是 setOrientation 已经被弃用,所以这不是一个好的解决方案。谢谢。 - A.Vila
2
@A.Vila,你在问题中提到了相机方向而不是预览层方向。仅供参考,AVCaptureSession创建了2个单独的连接(用于预览层和相机输出),您需要分别旋转两者!我已经更新了我的答案以适应预览层方向。 - Khaled Barazi
谢谢你的回答。我已经尝试了,但是出现了一个错误。我会更新问题并提供错误信息。你知道问题出在哪里吗?非常感谢。 - A.Vila
它在iOS 6上运行良好,谢谢。对于早期版本,这段代码可能会很有用:if([self.prevLayer isOrientationSupported]){             self.prevLayer.orientation = newOrientation;} - A.Vila
不喜欢倒置的肖像模式吗? 如果需要,可以添加第四种情况: case UIInterfaceOrientationPortraitUpsideDown:[previewLayerConnection setVideoOrientation:AVCaptureVideoOrientationPortraitUpsideDown];break; - Kpmurphy91
1
这段代码适用于iOS7和8.1。谢谢!//我使用“UIInterfaceOrientation interfaceOrientation = [self interfaceOrientation];”因为shouldAutorotateToInterfaceOrientation已弃用。 - ecth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接