iPhone AVFoundation camera orientation

前端 未结 12 637
走了就别回头了
走了就别回头了 2020-12-02 09:46

I\'ve been tearing my hair out trying to get the AVFoundation camera to capture a picture in the correct orientation (i.e. the device orientation) but I can\'t get it to wor

12条回答
  •  醉话见心
    2020-12-02 10:49

    Update the orientation in the preview layer after start the capture session and whenever the device is rotated.

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        coordinator.animate(alongsideTransition: { [weak self] context in
            if let connection = self?.previewLayer?.connection, connection.isVideoOrientationSupported {
                if let orientation = AVCaptureVideoOrientation(orientation: UIDevice.current.orientation) {
                    connection.videoOrientation = orientation
                }
            }
        }, completion: nil)
        super.viewWillTransition(to: size, with: coordinator)
    }
    
    extension AVCaptureVideoOrientation {
        init?(orientation: UIDeviceOrientation) {
            switch orientation {
            case .landscapeRight: self = .landscapeLeft
            case .landscapeLeft: self = .landscapeRight
            case .portrait: self = .portrait
            case .portraitUpsideDown: self = .portraitUpsideDown
            default: return nil
            }
        }
    }
    

提交回复
热议问题