I want to implement a simple pinch to zoom gesture in a QR app.
It seems simple, so I did some researches I found a few possible answers to the problem:
AVCaptureDevice Camera Zoom
How to implement "pinch to zoom" in custom camera
Pinch to zoom camera
Zooming while capturing video using AVCapture in iOS
Unfortunately none of those actually solve it as I wanted, I personally liked the first one (in Objective-C) and I tried to do it in Swift 3.
I posted an answer with the code that I came up with after some tries, other easier/better/simpler solutions are welcomed :)
I used the Pinch Gesture Recognizer
from the storyboard, then linked this action:
@IBAction func pinchToZoom(_ sender: UIPinchGestureRecognizer) {
guard let device = captureDevice else { return }
if sender.state == .changed {
let maxZoomFactor = device.activeFormat.videoMaxZoomFactor
let pinchVelocityDividerFactor: CGFloat = 5.0
do {
try device.lockForConfiguration()
defer { device.unlockForConfiguration() }
let desiredZoomFactor = device.videoZoomFactor + atan2(sender.velocity, pinchVelocityDividerFactor)
device.videoZoomFactor = max(1.0, min(desiredZoomFactor, maxZoomFactor))
} catch {
print(error)
}
}
}
Note that captureDevice
is an optional object of the class AVCaptureDevice
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With