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

标签 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: "com.bigbob.videoQueue")
            dataOutput.setSampleBufferDelegate(self, queue: queue)
        }
    } catch _ {
        print("Error setting up camera!")
    }

最佳答案

设置 videoZoomFactor您的 AVCaptureDevice.defaultDevice预览层的缩放也会随之而来。注意 Swift 4 现在被称为 AVCaptureDevice.default .

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

关于ios - 如何使用 AVCaptureVideoPreviewLayer 从相机应用程序实现 2 倍变焦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42843858/

相关文章:

iphone - 如何让自动对焦在第二个 AVCaptureSession 中工作而不重新创建 session ?

ios - 检测目标 View Controller viewWillAppear 中的向后/弹出导航

android - iOS 和 Android 之间的 Xamarin Forms 文本布局差异

ios - Swift 3 尝试将音频路径/音频文件传递给音频播放器 VC

IOS 8 iPad 仅制作 Launch Screen 人像

swift - 在 Swift 中通过下标访问单例属性

ios - 有没有办法在 Swift 中将 UIPickerView 添加到 UIAlertController(Alert 或 ActionSheet)中?

ios - 在 Spritekit 中横向显示 Game Center Modal View Controller 时没有键盘

swift - 如何在 AvCapture Session 运行时播放触觉反馈?

ios - 使用 AVCaptureVideoPreviewLayer 时如何保持捕获的视频大小