如何实现Pinch To Zoom in camera(Swift 3)?

时间:2017-04-07 12:52:30

标签: ios swift

我想在QR应用程序中实现一个简单的缩放缩放手势 这看起来很简单,所以我做了一些研究,我发现了一些问题的可能答案:

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

不幸的是,实际上并没有像我想的那样解决它, 我个人喜欢第一个(在Objective-C中),我试图在Swift 3中做到这一点。

我在一些尝试之后发布了我想出的代码的答案,欢迎其他更简单/更好/更简单的解决方案:)

2 个答案:

答案 0 :(得分:8)

我使用了故事板中的Pinch Gesture Recognizer,然后将此操作链接起来:

@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)
            }
        }
    }

请注意,captureDevice是类AVCaptureDevice的可选对象。

答案 1 :(得分:0)

@IBAction func pinchToZoom(_ sender: UIPinchGestureRecognizer) {

  guard let device = captureDevice else { return }

  func minMaxZoom(_ factor: CGFloat) -> CGFloat { return min(max(factor, 1.0), device.activeFormat.videoMaxZoomFactor) }

  func update(scale factor: CGFloat) {
    do {
      try device.lockForConfiguration()
      defer { device.unlockForConfiguration() }
      device.videoZoomFactor = factor
    } catch {
      debugPrint(error)
    } 
  }

  let newScaleFactor = minMaxZoom(pinch.scale * zoomFactor)

  switch sender.state {
    case .began: fallthrough
    case .changed: update(scale: newScaleFactor)
    case .ended:
      zoomFactor = minMaxZoom(newScaleFactor)
      update(scale: zoomFactor)
    default: break
  }
}