我的应用程序中有一个 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/