如何使用 AVCaptureVideoPreviewLayer 从相机应用程序实现 2 倍缩放

How to implement 2x zoom from camera app with AVCaptureVideoPreviewLayer

我的应用程序中有一个 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!")
    }

设置 AVCaptureDevice.defaultDevicevideoZoomFactor,预览图层的缩放将随之进行。注意 Swift 4 它现在被称为 AVCaptureDevice.default.

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