2014-11-25 48 views
1

我正在創建一個流程圖,當用戶拖動一個節點時,我想要移動連接到它的線。在節點的泛處理程序事件中,我實現了一個CGAffineTransform來變換行,但它不會平滑地移動行。任何想法如何其他流程圖應用程序處理這個問題?如何在平移手勢事件期間變換一條線?

func panHandler(sender: UIPanGestureRecognizer) { 

     else if (sender.state == .Changed) 
     { 
      let translation = sender.translationInView(self) 
      sender.view!.center = CGPointMake(originalCenter.x + translation.x, originalCenter.y + translation.y) 


      //rv is the connected line, created at an other place like: 
      //let w = GraphViewController.calcLength(e.x, y0: e.y, x1: e2.x, y1: e2.y) 
      //rv = UIView(frame: CGRectMake(0, 0, CGFloat(w), 1.0)) 
      //var angle = GraphViewController.calcAngle(e.x, y0: e.y, x1: e2.x, y1: e2.y) 
      //rv.transform = CGAffineTransformMakeRotation(CGFloat(angle)) 

      var angle = GraphViewController.calcAngle(e!.x, y0: e!.y, x1: r.destination!.x, y1:r.destination!.y) 
      rv!.transform = CGAffineTransformMakeRotation(CGFloat(angle)) 

     } 
    } 
+0

你嘗試把RV .transform = CGAffineTransformMakeRotation(CGFloat的(角度))爲動畫塊? – 2014-12-04 18:18:08

+0

您確定,該角度是以弧度測量的,但不是度數? CGAffineTransformMakeRotation所需的弧度角度。我不記得它是如何在Swift中看起來的,但是在Objective C中,它將如下所示: \t [UIView animateWithDuration:0.05動畫:^ { \t rv.transform = CGAffineTransformMakeRotation(M_PI * angle); \t}]; – 2014-12-06 13:20:22

回答

4

因爲你不需要線路上的任何觸摸事件,我們可以用一個簡單的CAShapeLayer並更新其對泛路徑。我假設你想要一些線路的錨點。

定義一些錨點的行

endOfLineAnchor = CGPoint(x: view.bounds.width/2, y: view.bounds.height * 0.8) 

創建一些觀點將其附加到

ballView = createBallView() 
ballView.center = CGPoint(x: view.bounds.width/2, y: view.bounds.height/2) 

添加圖層&視圖

lineLayer = CAShapeLayer() 
    lineLayer.strokeColor = UIColor.blackColor().CGColor 
    lineLayer.path = pathFromBallToAnchor() 
    view.layer.addSublayer(lineLayer) 
    view.addSubview(ballView) 

潘更新層的路徑

else if (sender.state == .Changed) 
    { 
     let translation = sender.translationInView(self.view) 
     sender.view!.center = CGPointMake(originalCenter.x + translation.x, originalCenter.y + translation.y) 
     CATransaction.begin() 
     CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) 
     lineLayer.path = pathFromBallToAnchor() 
     CATransaction.commit() 
    } 

CATransaction的原因是我們要禁用隱式動畫。

構建路徑:

func pathFromBallToAnchor() -> CGPathRef { 
     var bazier = UIBezierPath() 
     bazier.moveToPoint(ballView.center) 
     bazier.addLineToPoint(endOfLineAnchor) 
     return bazier.CGPath 
    } 

結果:

Panned Ball attached to an anchored line in iPhone 5 iOS 8.1 simulator

+2

該代碼可以在https://github.com/iamdoron/panABallAttachedToALine找到 – surui 2014-12-11 08:59:11