无法为AVCaptureVideoPreviewLayer设置边界

时间:2018-05-10 18:22:34

标签: ios swift

我很难改变AVCaptureVideoPreviewLayer的界限。无论我做什么,它总是以小尺寸结束,如下所示:

enter image description here

这是我的代码:

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.imageLayer.bounds = CGRect(x: 0, y: 0, width: 375, height: 100)
    }

    private func startLiveVideo() {

        session.sessionPreset = AVCaptureSession.Preset.photo
        let captureDevice = AVCaptureDevice.default(for: AVMediaType.video)

        let deviceInput = try! AVCaptureDeviceInput(device: captureDevice!)
        let deviceOutput = AVCaptureVideoDataOutput()
        deviceOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA)]
        deviceOutput.setSampleBufferDelegate(self, queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))
        session.addInput(deviceInput)
        session.addOutput(deviceOutput)

        self.imageLayer = AVCaptureVideoPreviewLayer(session: session)
        imageLayer.frame = CGRect(x: 0, y: 0, width: 375, height: 100)
        self.imageView.layer.addSublayer(self.imageLayer)

        session.startRunning()
    }

解决方案:

self.imageLayer.videoGravity = .resizeAspectFill

1 个答案:

答案 0 :(得分:0)

您可以先从故事板或 yourViewController 500 x 500或任何您想要的尺寸指定 imageView 的宽度和高度。

imageLayer.frame = CGRect(x: 0, y: 0, width: self.imageView.frame.width, height: self.imageView.frame.height)

self.imageView.layer.addSublayer(self.imageLayer)