如何快速修改PreviewView?

时间:2019-06-18 07:59:53

标签: swift avfoundation

我正在构建相机应用。
我想预览和1:1相框。
但是我该怎么办?

我已经尝试过更改PreviewView框架。

self.previewView?.frame.size = CGSize(width: 300, height: 300)

但是它不起作用。

class CameraViewController: UIViewController {
    // MARK: - Properties
    // MARK: Declared

    var captureSession: AVCaptureSession?
    var captureOutput: AVCapturePhotoOutput?

    // MARK: IBOutlet

    @IBOutlet weak var previewView: PreviewView!



    // MARK: - Methods
    // MARK: View Life Cycle

    override func viewDidLoad() {
        super.viewDidLoad()

        self.configureInput()
        self.configureOutput()
        self.configurePreview()
        self.runCamera()
    }

    // MARK: Configure

    private func configureInput() {
        self.captureSession = AVCaptureSession()
        self.captureSession?.beginConfiguration()
        self.captureSession?.sessionPreset = .hd4K3840x2160
        guard let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else { return }
        guard let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice), self.captureSession?.canAddInput(videoDeviceInput) == true else { return }
        self.captureSession?.addInput(videoDeviceInput)
    }

    private func configureOutput() {
        let photoOutput = AVCapturePhotoOutput()
        self.captureOutput = photoOutput
        guard self.captureSession?.canAddOutput(photoOutput) == true else { return }
        self.captureSession?.sessionPreset = .photo
        self.captureSession?.addOutput(photoOutput)
        self.captureSession?.commitConfiguration()
    }

    private func configurePreview() {
        self.previewView?.videoPreviewlayer.session = self.captureSession
    }

    private func runCamera() {
        self.captureSession?.startRunning()
    }

}

这是我的代码。
我在苹果的文章之后读了这篇文章。 (https://developer.apple.com/documentation/avfoundation/cameras_and_media_capture/setting_up_a_capture_session

1 个答案:

答案 0 :(得分:2)

您可以使用它来更改预览图层框架,使其充满您的预览视图:

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        previewLayer.frame = cameraView.bounds
        previewLayer.videoGravity = .resizeAspectFill
}