I\'m trying to make a pinch to zoom camera but I\'m encountering two problems. First is that it allows the user to zoom way too much in and way to much out, secondly when I take
To expand on Ritvik Upadhyaya's answer, you would also need to save the previous zoom factor to calculate the new one, you wouldn't want the zooming to reset to normal every time you lift up your fingers and try zooming again.
// To track the zoom factor
var prevZoomFactor: CGFloat = 1
func pinch(pinch: UIPinchGestureRecognizer) {
var device: AVCaptureDevice = self.videoDevice
// Here we multiply vZoomFactor with the previous zoom factor if it exist.
// Else just multiply by 1
var vZoomFactor = pinch.scale * prevZoomFactor
// If the pinching has ended, update prevZoomFactor.
// Note that we set the limit at 1, because zoom factor cannot be less than 1 or the setting device.videoZoomFactor will crash
if sender.state == .ended {
prevZoomFactor = zoomFactor >= 1 ? zoomFactor : 1
}
do {
try device.lockForConfiguration()
defer {device.unlockForConfiguration()}
if (vZoomFactor <= device.activeFormat.videoMaxZoomFactor) {
device.videoZoomFactor = vZoomFactor
} else {
print("Unable to set videoZoom: (max \(device.activeFormat.videoMaxZoomFactor), asked \(vZoomFactor))")
}
} catch {
print("\(error.localizedDescription)")
}
}