如何在旋转后调整相机纵横比?

时间:2018-02-08 05:41:38

标签: ios iphone swift video-capture screen-orientation

我有一个小的Swift程序来捕捉视频。如果我在横向模式下使用手机启动应用程序,那么我将获得全屏

enter image description here

但是当我将手机旋转到纵向时,它不会填满整个屏幕。

enter image description here

我尝试过resizeAspectFill,但它不起作用。 我怀疑当我将屏幕旋转到新的宽高比时我必须改变宽高比,但似乎找不到任何成功的例子。

有人可以帮忙吗?

示例代码如下所示:

    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill

    let orientation: UIDeviceOrientation = UIDevice.current.orientation

    switch (orientation) {
    case .portrait:
        cameraPreviewLayer?.connection?.videoOrientation = .portrait
    case .landscapeRight:
        cameraPreviewLayer?.connection?.videoOrientation = .landscapeLeft
    case .landscapeLeft:
        cameraPreviewLayer?.connection?.videoOrientation = .landscapeRight
    case .portraitUpsideDown:
        cameraPreviewLayer?.connection?.videoOrientation = .portraitUpsideDown
    default:
        cameraPreviewLayer?.connection?.videoOrientation = .portraitUpsideDown
    }

    cameraPreviewLayer?.frame = self.view.frame

    self.view.layer.insertSublayer(cameraPreviewLayer!, at: 0)

感谢。

1 个答案:

答案 0 :(得分:0)

尝试将这些代码移至viewDidLayoutSubviews

override func viewDidLayoutSubviews() {
    let orientation: UIDeviceOrientation = UIDevice.current.orientation

    switch (orientation) {
    case .portrait:
        cameraPreviewLayer?.connection?.videoOrientation = .portrait
    case .landscapeRight:
        cameraPreviewLayer?.connection?.videoOrientation = .landscapeLeft
    case .landscapeLeft:
        cameraPreviewLayer?.connection?.videoOrientation = .landscapeRight
    case .portraitUpsideDown:
        cameraPreviewLayer?.connection?.videoOrientation = .portraitUpsideDown
    default:
        cameraPreviewLayer?.connection?.videoOrientation = .portraitUpsideDown
    }

    cameraPreviewLayer?.frame = self.view.frame
}