如何在自定义 UIView 中居中 VideoPreviewLayer(故事板 Swift)

How To Center VideoPreviewLayer in Custom UIView (Storyboard Swift)

如何在现有 UIView 中将 videoPreviewLayer 居中?我尝试了以下方法,但它比我想要的要小。



        var videoPreviewLayer : AVCaptureVideoPreviewLayer?

        let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)
        do {
            let input = try AVCaptureDeviceInput(device: captureDevice!)
            captureSession = AVCaptureSession()
            captureSession?.addInput(input)
            videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
//            let frame : CGRect = self.scanView.layer.bounds
//            videoPreviewLayer?.frame = frame
            videoPreviewLayer?.frame = self.scanView.bounds
//            videoPreviewLayer?.bounds = self.view.bounds

            scanView.layer.addSublayer(videoPreviewLayer!)
            captureSession?.startRunning()
        } catch {
            print("error-jz")
        }

        capturePhotoOutput = AVCapturePhotoOutput()
        capturePhotoOutput?.isHighResolutionCaptureEnabled = true
        captureSession?.addOutput(capturePhotoOutput!)```

它应该在您添加 videoPreviewLayer 的任何视图中居中。但是当你说它比你想要的小时,那可能是因为你没有为播放器层设置视频重力。

videoPreviewLayer.videoGravity = .resizeAspectFill

这将使视频预览填满它所包含的整个视图。如果它仍然没有按照您想要的方式居中,您可能必须修复 UIView 本身的居中。