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
1. Define zoom levels.
let minimumZoom: CGFloat = 1.0
let maximumZoom: CGFloat = 3.0
var lastZoomFactor: CGFloat = 1.0
2. Add Pinch Gesture on CameraView.
let pinchRecognizer = UIPinchGestureRecognizer(target: self, action:#selector(pinch(_:)))
self.viewCamera.addGestureRecognizer(pinchRecognizer)
3. Pinch-action method with the logic of zoomin
and zoom out
func pinch(_ pinch: UIPinchGestureRecognizer) {
guard let device = videoDeviceInput.device else { return }
// Return zoom value between the minimum and maximum zoom values
func minMaxZoom(_ factor: CGFloat) -> CGFloat {
return min(min(max(factor, minimumZoom), maximumZoom), device.activeFormat.videoMaxZoomFactor)
}
func update(scale factor: CGFloat) {
do {
try device.lockForConfiguration()
defer { device.unlockForConfiguration() }
device.videoZoomFactor = factor
} catch {
print("\(error.localizedDescription)")
}
}
let newScaleFactor = minMaxZoom(pinch.scale * lastZoomFactor)
switch pinch.state {
case .began: fallthrough
case .changed: update(scale: newScaleFactor)
case .ended:
lastZoomFactor = minMaxZoom(newScaleFactor)
update(scale: lastZoomFactor)
default: break
}
}
Thanks. Happy coding