Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect and apply landscape orientation to AVCaptureVideoPreviewLayer in Swift?

I'm basically after the answer to this question AVCaptureVideoPreviewLayer orientation - need landscape except in Swift.

I'm targeting iOS 8 and AVCaptureVideoPreviewLayer doesn't seem to have a setVideoOrientation function.

How should I be detecting that the orientation has changed, and rotating AVCaptureVideoPreviewLayer appropriately?

like image 985
epalm Avatar asked Aug 12 '15 03:08

epalm


1 Answers

Detect and apply it at viewWillLayoutSubviews or if you're using UIView subclass in layoutSubviews.

Here's how:

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

    previewLayer.connection?.videoOrientation = {
        switch (orientation) {
        case .portrait:
            return .portrait
        case .landscapeRight:
            return .landscapeLeft
        case .landscapeLeft:
            return .landscapeRight
        default:
            return .portrait
        }
    }()
}
like image 139
米米米 Avatar answered Oct 19 '22 03:10

米米米