如何修改swift中的previewView?

How to modify previewView in swift?

我正在构建相机应用程序。
我要预览和相框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)

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

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

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