相机只在人像模式下工作

Camera just works in Portrait mode

我的相机在人像模式下是这样的:

在横屏模式下也是如此:

所以我的问题是:

  1. 如何在横向模式下全屏设置 previewLayer?
  2. 为什么我旋转设备时相机不旋转?它始终保持纵向模式

确保 phone 的 "portrait orientation lock" 已关闭。并确保该应用程序允许在项目设置 > 常规选项卡中横向显示。

每次更改设备方向时,您都应该设置 AVCaptureSession 方向。

添加通知观察器以观察设备方向的任何变化,然后根据设备方向设置AVCaptureSession方向。

Obj-C:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(orientationChanged)
                                             name:UIDeviceOrientationDidChangeNotification
                                           object:nil];
-(void) orientationChanged
{
    if (self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationPortraitUpsideDown];

    if (self.interfaceOrientation == UIInterfaceOrientationPortrait)
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationPortrait];

    if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationLandscapeLeft];

    if (self.interfaceOrientation == UIInterfaceOrientationLandscapeRight)
        [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight];
}

Swift 2:

在某处添加观察者,例如在 viewDidLoad 方法中。

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(orientationChanged), name: UIDeviceOrientationDidChangeNotification, object: nil)

然后:

func orientationChanged(){
    let deviceOrientation = UIDevice.currentDevice().orientation

    if deviceOrientation == UIDeviceOrientation.PortraitUpsideDown {
        previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown
    }
    else if deviceOrientation == UIDeviceOrientation.Portrait {
        previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
    }
    else if deviceOrientation == UIDeviceOrientation.LandscapeLeft {
        previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeLeft
    }
    else if deviceOrientation == UIDeviceOrientation.LandscapeRight {
        previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
    }
}

您还可以提供您的任何代码或查看此问题,该问题可能会有所帮助。 AVCaptureSession with multiple orientations issue