3

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
                    do{
                        try device.lockForConfiguration()
                        if vZoomFactor <= device.activeFormat.videoMaxZoomFactor {
                            device.videoZoomFactor = vZoomFactor
                            device.unlockForConfiguration()
                        }
                    }catch _{
                    }
                }

            }
        }
cb428
  • 485
  • 1
  • 6
  • 19

2 Answers2

3

You have to set videoZoomFactor by based on former value.

do {
    try device.lockForConfiguration()
    switch gesture.state {
    case .began:
        self.pivotPinchScale = device.videoZoomFactor
    case .changed:
        var factor = self.pivotPinchScale * gesture.scale
        factor = max(1, min(factor, device.activeFormat.videoMaxZoomFactor))
        device.videoZoomFactor = factor
    default:
        break
    }
    device.unlockForConfiguration()
} catch {
    // handle exception
}

You should have saved former scale factor in order to start zoom in/out from current zoom state, self.pivotPinchScale in above example is the key. I wish you can get some hints from following example.

https://github.com/DragonCherry/CameraPreviewController

DragonCherry
  • 742
  • 7
  • 10
0

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