2012-09-10 69 views
10

當使用UIPinchGestureRecognizer時,在水平和垂直方向上分別檢測/讀取比例尺的最佳方法是什麼?我看到這個帖子UIPinchGestureRecognizer分別在水平和垂直方向上的比例尺

UIPinchGestureRecognizer Scale view in different x and y directions

但我注意到有這麼多來回的,我不知道那是最好的答案/辦法這樣一個看似例行的任務。

如果完全沒有使用UIPinchGestureRecognizer來達到這個目的就是答案,那麼在兩個不同的方向上檢測縮放比例的最好方法是什麼?

回答

2

在我的C#我下面

private double _firstDistance = 0; 
    private int _firstScaling = 0; 
    private void PinchHandler(UIPinchGestureRecognizer pinchRecognizer) 
    { 
     nfloat x1, y1, x2, y2 = 0; 
     var t1 = pinchRecognizer.LocationOfTouch(0, _previewView); 
     x1 = t1.X; 
     y1 = t1.Y; 
     var t2 = pinchRecognizer.LocationOfTouch(1, _previewView); 
     x2 = t2.X; 
     y2 = t2.Y; 

     if (pinchRecognizer.State == UIGestureRecognizerState.Began) 
     { 
      _firstDistance = Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2)); 
      _firstScaling = _task.TextTemplates[_selectedTextTemplate].FontScaling; 
     } 
     if (pinchRecognizer.State == UIGestureRecognizerState.Changed) 
     { 
      var distance = Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2)); 
      var fontScaling = Convert.ToInt32((distance - _firstDistance)/_previewView.Frame.Height * 100); 
      fontScaling += _firstScaling; 
      _task.TextTemplates[_selectedTextTemplate].FontScaling = fontScaling; 
      UpdateBitmapPreview(); 
     } 
    } 

我計算這兩個點之間的距離的時候捏「開始」,並在兩個士兵認爲值。然後我根據第一個測量距離和第二個測量距離(「更改」)計算縮放比例(fontScaling)。 我使用我自己的視圖(_previewView)設置爲基礎(100%),但是您可以使用View.Bounds.height而不是此寬度。在我的情況下,我總是有一個方形視圖,所以我的應用程序中的高度==寬度。

1

基本上做到這一點,

func _mode(_ sender: UIPinchGestureRecognizer)->String { 

    // very important: 
    if sender.numberOfTouches < 2 { 
     print("avoided an obscure crash!!") 
     return "" 
    } 

    let A = sender.location(ofTouch: 0, in: self.view) 
    let B = sender.location(ofTouch: 1, in: self.view) 

    let xD = fabs(A.x - B.x) 
    let yD = fabs(A.y - B.y) 
    if (xD == 0) { return "V" } 
    if (yD == 0) { return "H" } 
    let ratio = xD/yD 
    // print(ratio) 
    if (ratio > 2) { return "H" } 
    if (ratio < 0.5) { return "V" } 
    return "D" 
} 

該函數將返回H,V,d爲你..水平,垂直,對角。

你會使用它像這樣...

func yourSelector(_ sender: UIPinchGestureRecognizer) { 

    // your usual code such as .. 
    // if sender.state == .ended { return } .. etc 

    let mode = _mode(sender) 
    print("the mode is \(mode) !!!") 

    // in this example, we only care about horizontal pinches... 
    if mode != "H" { return } 

    let vel = sender.velocity 
    if vel < 0 { 
     print("you're squeezing the screen!") 
    } 
}