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

时间:2017-03-16 20:09:23

标签: ios swift avcapturesession

我的应用程序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: "edu.hawaii.yuep.videoQueue")
            dataOutput.setSampleBufferDelegate(self, queue: queue)
        }
    } catch _ {
        print("Error setting up camera!")
    }

1 个答案:

答案 0 :(得分:1)

使用以下设置AVCapture设备的缩放属性,预览图层的缩放也将跟随。

double