ios - 无法为 AVCaptureVideoPreviewLayer 设置边界

标签 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

最佳答案

您可以首先从 Storyboard 或通过 yourViewController 分配 imageView 的宽度和高度 500 x 500 或您想要的任何大小。

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

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

关于ios - 无法为 AVCaptureVideoPreviewLayer 设置边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50279227/

相关文章:

ios - SwiftUI - @Binding :String from DatePickerView

ios - NSURLSession 下载任务-进度条问题

ios - Swift 中 BLE 的后台扫描

swift - 使用 Float 数组在 Swift 中调用 "realloc"的正确方法?

swift - 让我们输入一个 for in 循环

ios - 类型 `Int` 的不可变值只有名为 adjust 的可变成员

ios - mapViewDidFailLoadingMap 中的 UIAlertView :withError:

ios - UIScrollView的zoomScale不一致

ios - Swift 中 UITableView 的动态数据源交换

objective-c - 用于 Cocoa OS x 的语音到文本转录 API