ios 如何使用AVCaptureVideoPreviewLayer从相机应用程序实现2倍变焦

gblwokeq  于 2023-02-26  发布在  iOS
关注(0)|答案(2)|浏览(392)

我的应用程序中有一个AVCaptureVideoPreviewLayer,它运行良好,显示的预览视频与相机应用程序相同。我想实现相机应用程序的2倍变焦功能。如何实现?
基本上,我希望我的预览层改变视频饲料相同的规模,你看到在相机应用程序时,你点击1X图标,以改变它为2X。
设置预览图层

func startSession(){
    captureSession = AVCaptureSession()
    captureSession?.sessionPreset = AVCaptureSessionPresetPhoto
    
    let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
    
    // Catch error using the do catch block
    do {
        let input = try AVCaptureDeviceInput(device: backCamera)
        if (captureSession?.canAddInput(input) != nil){
            captureSession?.addInput(input)
            
            // Setup the preview layer
            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
            previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
            tempImageView.layer.addSublayer(previewLayer!)
            captureSession?.startRunning()
            
            // Set up AVCaptureVideoDataOutput
            let dataOutput = AVCaptureVideoDataOutput()
            dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString) : NSNumber(value: kCVPixelFormatType_32BGRA as UInt32)]
            dataOutput.alwaysDiscardsLateVideoFrames = true
            
            if (captureSession?.canAddOutput(dataOutput) == true) {
                captureSession?.addOutput(dataOutput)
            }
            let queue = DispatchQueue(label: "com.bigbob.videoQueue")
            dataOutput.setSampleBufferDelegate(self, queue: queue)
        }
    } catch _ {
        print("Error setting up camera!")
    }
fv2wmkja

fv2wmkja1#

设置你的AVCaptureDevice.defaultDevicevideoZoomFactor,预览图层的缩放也会跟着做。注意Swift 4现在叫AVCaptureDevice.default

do {
    try backCamera?.lockForConfiguration()
    let zoomFactor:CGFloat = 2
    backCamera?.videoZoomFactor = zoomFactor
    backCamera?.unlockForConfiguration()
} catch {
       //Catch error from lockForConfiguration
}
6ie5vjzr

6ie5vjzr2#

这里有一个更新的答案,首先检查以确保缩放因子是可用的,甚至在你试图设置它之前。这将防止可能不必要的异常捕获,你可以调整缩放检查和设置容易与一个变量。

if let captureDevice = AVCaptureDevice.default(for: AVMediaType.video) {
    let zoomFactor : CGFloat = 2
    if (captureDevice.maxAvailableVideoZoomFactor >= zoomFactor) {
        try? captureDevice.lockForConfiguration()
        captureDevice.videoZoomFactor = zoomFactor
        captureDevice.unlockForConfiguration()
    }
}

相关问题