Search code examples
iosiphoneswiftvideo-capturescreen-orientation

How to resize camera aspect ratio after rotation?


I have a little Swift program to capture videos. If I start the app with the phone in Landscape mode, then I get the full screen

enter image description here

but when I rotate the phone to Portrait, it doesn't fill the whole screen.

enter image description here

I've tried with resizeAspectFill but it doesn't work. I suspect I have to change the aspect ratio when I rotate the screen to the new aspect ratio but can't seem to find any examples which successfully does it.

Can anyone help please?

The sample code looks something like this:

    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)

Thanks.


Solution

  • Try moving these code to 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
    }