2016-02-06 93 views
2

我有一個自定義的照片/視頻攝像頭(想想Snapchat)與縮放識別器放大/縮小。下面是一帆風順的事情基於一些代碼,我在網上找到:如何在自定義相機中實現「捏縮放」

  • 在一定程度上放大工作正常
  • 捕捉的圖像捕捉放大的圖像

這裏的什麼錯誤,我需要幫助:

  • 縮小導致崩潰
  • 雖然在作品放大,似乎重置,如果我放大變焦,停止觸摸屏幕,然後嘗試再次放大。
  • 捕獲視頻復位變焦

這是我的捏放碼,應該怎樣改?

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

      } 
     } 

回答

0

當您縮小pinch.scale值將變得小於1.0,那麼應用程序將崩潰。

方法-1

//just change this line 
if pinch.scale > 1.0 { 
    device.videoZoomFactor = vZoomFactor 
} else { 
    device.videoZoomFactor = 1.0 + vZoomFactor 
} 

方法 - 2

可以實現通過變換avcapturesession預覽層擠捏縮放。

yourPreviewLayer.affineTransForm = CGAffineTransformMakeScale(1.0 + pinch.scale.x, 1.0 +pinch.scale.y) 

當視頻捕獲方法調用預覽層變換爲標識。所以它會重置縮放。

yourPreviewLayer.affineTransForm = CGAffineTransformIdentity 
3

您必須根據以前的值設置videoZoomFactor。

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 
} 

你應該爲了開始放大,從當前的縮放狀態/,self.pivotPinchScale在上面的例子中是關鍵保存原比例因子。 我希望你能從下面的例子中得到一些提示。

https://github.com/DragonCherry/CameraPreviewController