4

我正在开发一个增强现实游戏,当设备的方向锁定打开时,我遇到了相机视图方向的问题。

我正在使用此代码在视图中加载相机视图:

AVCaptureSession *session = [[AVCaptureSession alloc] init];
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.frame = self.sessionView.bounds;
[self.sessionView.layer addSublayer:captureVideoPreviewLayer];
CGRect bounds=sessionView.layer.bounds;
captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
captureVideoPreviewLayer.bounds=bounds;
captureVideoPreviewLayer.orientation = [[UIDevice currentDevice] orientation];
captureVideoPreviewLayer.position=CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// device.position ;
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if ([device hasTorch]) {
    ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset1280x720]);
}
else {
    ([device supportsAVCaptureSessionPreset:AVCaptureSessionPreset640x480]);
}
[session addInput:input];
[session startRunning];

为了使应用程序的方向保持正确,我只选择了 Xcode 应用程序摘要中的那个框,其中包含:

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

当设备开启方向锁定(双击主页按钮,向右滑动,点击方向图标)时,相机视图是纵向的,而游戏的其余部分是横向的。有没有什么办法解决这一问题?从我读过的内容来看,用户打开游戏时无法关闭方向锁定。

4

1 回答 1

16

预览层不定向的原因是因为您使用的是已弃用的 API,而且您没有在设备方向更改时更新视频方向。

  1. 删除已弃用的 API,即在您的代码中,而不是

    captureVideoPreviewLayer.orientation
    

    使用 videoOrientation 属性,即

    captureVideoPreviewLayer.connection.videoOrientation 
    
  2. 更新 shouldAutorotate 中的视频方向,如下所示:

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
    
        if(interfaceOrientation == UIInterfaceOrientationLandscapeRight)
        {
           captureVideoPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight
        }
    
          // and so on for other orientations
    
        return ((interfaceOrientation == UIInterfaceOrientationLandscapeRight));
    }
    
于 2012-12-12T07:19:58.823 回答