cb428
cb428

Reputation: 495

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:

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

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 _{
                    }
                }

            }
        }

Upvotes: 3

Views: 4324

Answers (2)

DragonCherry
DragonCherry

Reputation: 802

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

Upvotes: 3

mahbaleshwar hegde
mahbaleshwar hegde

Reputation: 711

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

Upvotes: 0

Related Questions