Search code examples
iosiphoneswiftcamerazooming

Pinch to zoom camera


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 a picture it doesn't take it of the zoomed in view. Here is my code for the pinch function...

func pinch(pinch: UIPinchGestureRecognizer) {
    if let view = cameraView {
        view.transform = CGAffineTransformScale(view.transform,
            pinch.scale, pinch.scale)
            pinch.scale = 1
    }

}

Tell me if you need to see any more code. Thanks!


Solution

  • I have experienced the same issues with the camera implementation. To solve this you need to know about two things.

    • The max and min zoom has to be within a value or else it results in the camera zooming in way too much.
    • As with the actual image not saving the zoomed in image, it is a common bug a lot of solutions online do not cover. This is actually because you are only changing the view's zoom and not the actual AVCaptureDevice's zoom.

    To change the two things you need something like this:

    func pinch(pinch: UIPinchGestureRecognizer) {
       var device: AVCaptureDevice = self.videoDevice
       var vZoomFactor = ((gestureRecognizer as! UIPinchGestureRecognizer).scale)
       var error:NSError!
            do{
                try device.lockForConfiguration()
                defer {device.unlockForConfiguration()}
                if (vZoomFactor <= device.activeFormat.videoMaxZoomFactor){
                    device.videoZoomFactor = vZoomFactor
                }else{
                NSLog("Unable to set videoZoom: (max %f, asked %f)", device.activeFormat.videoMaxZoomFactor, vZoomFactor);
                }
            }catch error as NSError{
                 NSLog("Unable to set videoZoom: %@", error.localizedDescription);
            }catch _{
    
            }
    }
    

    As you can see I use a class variable for the video device (videoDevice) to keep track of the capture device I am using for visual component. I restrict the zoom to a particular range and change the zoom property on the device and not the view itself!