首页 > 解决方案 > 如何使用 swift 以纵向模式捕获图像

问题描述

我已经使用了 Apple 的 AVCam 模型,并在我的相机应用程序中实现了肖像模式。但问题是拍摄的图像不会是人像模式,而是像普通相机拍摄的那样。后来我发现我可以通过进入编辑部分并选择“人像”选项来激活人像模式。我希望以纵向模式保存图片。我怎样才能做到这一点?

标签: iosswift

解决方案


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(MainCameraVC.orientationChanged(notification:)), name: Notification.Name.UIDeviceOrientationDidChange, object: nil)
    }

    func orientationChanged(notification: Notification) {
        let deviceOrientation = UIDevice.current.orientation
        var angle: Double?

        switch deviceOrientation {
        case .portrait:
            angle = 0
            break
        case .portraitUpsideDown:
            angle = Double.pi
            break
        case .landscapeLeft:
            angle = Double.pi / 2
            break
        case .landscapeRight:
            angle = -Double.pi / 2
            break
        default:
            break
        }

        if let angle = angle {
            let transform = CGAffineTransform(rotationAngle: CGFloat(angle))

            UIView.animate(withDuration: 0.3, animations: {
                self.label.transform = transform
                self.button.transform = transform
                ...
            })
        }
    }
}

推荐阅读