Pinch to zoom camera

后端 未结 6 1491
再見小時候
再見小時候 2021-02-07 13:51

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

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 14:57

    Swift 3.0 || 4.0


    1. Define zoom levels.

    let minimumZoom: CGFloat = 1.0
    let maximumZoom: CGFloat = 3.0
    var lastZoomFactor: CGFloat = 1.0
    


    2. Add Pinch Gesture on CameraView.

    let pinchRecognizer = UIPinchGestureRecognizer(target: self, action:#selector(pinch(_:)))        
                self.viewCamera.addGestureRecognizer(pinchRecognizer)
    


    3. Pinch-action method with the logic of zoomin and zoom out

    func pinch(_ pinch: UIPinchGestureRecognizer) {
            guard let device = videoDeviceInput.device else { return }
    
            // Return zoom value between the minimum and maximum zoom values
            func minMaxZoom(_ factor: CGFloat) -> CGFloat {
                return min(min(max(factor, minimumZoom), maximumZoom), device.activeFormat.videoMaxZoomFactor)
            }
    
            func update(scale factor: CGFloat) {
                do {
                    try device.lockForConfiguration()
                    defer { device.unlockForConfiguration() }
                    device.videoZoomFactor = factor
                } catch {
                    print("\(error.localizedDescription)")
                }
            }
    
            let newScaleFactor = minMaxZoom(pinch.scale * lastZoomFactor)
    
            switch pinch.state {
            case .began: fallthrough
            case .changed: update(scale: newScaleFactor)
            case .ended:
                lastZoomFactor = minMaxZoom(newScaleFactor)
                update(scale: lastZoomFactor)
            default: break
            }
        }
    


    Thanks. Happy coding

提交回复
热议问题