Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Pinch To Zoom in camera (Swift 3)?

Tags:

ios

swift

I want to implement a simple pinch to zoom gesture in a QR app.
It seems simple, so I did some researches I found a few possible answers to the problem:

AVCaptureDevice Camera Zoom
How to implement "pinch to zoom" in custom camera
Pinch to zoom camera
Zooming while capturing video using AVCapture in iOS

Unfortunately none of those actually solve it as I wanted, I personally liked the first one (in Objective-C) and I tried to do it in Swift 3.

I posted an answer with the code that I came up with after some tries, other easier/better/simpler solutions are welcomed :)

like image 811
Daniel Illescas Avatar asked Sep 19 '25 03:09

Daniel Illescas


1 Answers

I used the Pinch Gesture Recognizer from the storyboard, then linked this action:

@IBAction func pinchToZoom(_ sender: UIPinchGestureRecognizer) {

        guard let device = captureDevice else { return }

        if sender.state == .changed {

            let maxZoomFactor = device.activeFormat.videoMaxZoomFactor
            let pinchVelocityDividerFactor: CGFloat = 5.0

            do {

                try device.lockForConfiguration()
                defer { device.unlockForConfiguration() }

                let desiredZoomFactor = device.videoZoomFactor + atan2(sender.velocity, pinchVelocityDividerFactor)
                device.videoZoomFactor = max(1.0, min(desiredZoomFactor, maxZoomFactor))

            } catch {
                print(error)
            }
        }
    }

Note that captureDevice is an optional object of the class AVCaptureDevice.

like image 154
Daniel Illescas Avatar answered Sep 20 '25 19:09

Daniel Illescas