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

How to resize camera aspect ratio after rotation?

我有一个 Swift 小程序可以捕捉视频。如果我在横向模式下使用 phone 启动应用程序,那么我会得到全屏

但是当我将 phone 旋转到纵向时,它并没有填满整个屏幕。

我试过使用 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)

谢谢。

尝试将这些代码移动到 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
}