Home Ask Login Register

Developers Planet

Your answer is one click away!

cb428 February 2016

How to implement "pinch to zoom" in custom camera

I have a custom photo/video camera (think Snapchat) with a pinch recognizer to zoom in/out. Here's what's going right based on some code I found online:

  • Zooming in somewhat works properly
  • Capturing an image captures the zoomed image

Here's what's going wrong that I need help with:

  • Zoom out causes crash
  • Although zooming in works, it seems to reset the zoom if I zoom in, stop touching the screen, then try to zoom in again.
  • Capturing video resets the zoom

This is my code for the pinch gesture, what should be changed?

for input in self.captureSession.inputs {
            // check that the input is a camera and not the audio
            if input.device == self.frontCameraDevice || input.device == self.backCameraDevice {

                if pinch.state == UIGestureRecognizerState.Changed {

                    let device: AVCaptureDevice = input.device
                    let vZoomFactor = pinch.scale
                        try device.lockForConfiguration()
                        if vZoomFactor <= device.activeFormat.videoMaxZoomFactor {
                            device.videoZoomFactor = vZoomFactor
                    }catch _{



mahbaleshwar hegde February 2016

When you zoom out pinch.scale value will become less than 1.0, then app will crash.

Method -1

 //just change this line
 if pinch.scale > 1.0 {
  device.videoZoomFactor = vZoomFactor
 } else {
  device.videoZoomFactor = 1.0 + vZoomFactor

Method - 2

You can achieve the pinch zoom by transforming avcapturesession preview layer.

 yourPreviewLayer.affineTransForm = CGAffineTransformMakeScale(1.0 + pinch.scale.x, 1.0 +pinch.scale.y)

when video capture method calls change preview layer transform to identity. so it will reset the zoom.

 yourPreviewLayer.affineTransForm = CGAffineTransformIdentity

Post Status

Asked in February 2016
Viewed 3,974 times
Voted 13
Answered 1 times


Leave an answer

Quote of the day: live life