2017-05-14 12 views
3

OK、UIBezierPathsの新機能ですが、ユーザーの指の位置に応じてエンドポイントが更新されるパスが必要です。それはtouchesMovedSwift UIView:人の指の終わりに常にパスを作成しますか?

に変更する必要がありますこれまでのところ私が持っている:

func customInit() { 
    print("init scene") 
    self.backgroundColor = UIColor.cyan 

    path.move(to: CGPoint(x: 0, y: 0)) 
    path.addLine(to: CGPoint(x: 300, y: 300)) 

    let shapeLayer = CAShapeLayer() 
    shapeLayer.path = path.cgPath 
    shapeLayer.strokeColor = UIColor.blue.cgColor 
    shapeLayer.lineWidth = 3.0 

    self.layer.addSublayer(shapeLayer) 
} 

override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 

    var touch : UITouch! = touches.first! as UITouch 
    var location = touch.location(in: self) 

    path.move(to: location) 
} 

は、私は、これは、パスのエンドポイントを更新するだろうと思ったが、何も、元の線を引く超え起こりません。私はこれにSKSceneを使用したくないですが、何がうまくいかないのか分かりません。

どのようにすれば、いつでもユーザーのタップの位置にポイントを置くことができますか?

答えて

2

あなたは非常に近いです!あなたはいくつかのものを欠いている。

touchesMovedが呼び出された場合は、パスを更新してCAShapeLayerに再割り当てして再描画する必要があります。今はパスオブジェクトを変更しているだけですが、再描画はしません。 (Xcodeの8.3.2遊び場で試験)

ファイナルコード

class DrawingView: UIView { 

    let startingPoint = CGPoint(x: 0, y: 0) 

    let shapeLayer = CAShapeLayer() 
    let path = UIBezierPath() 

    override init(frame: CGRect) { 
     super.init(frame: frame) 
     customInit() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     customInit() 
    } 

    func customInit() { 

     backgroundColor = UIColor.cyan 

     path.move(to: startingPoint) 
     path.addLine(to: CGPoint(x: 50, y: 50)) 

     shapeLayer.path = path.cgPath 
     shapeLayer.strokeColor = UIColor.blue.cgColor 
     shapeLayer.lineWidth = 3.0 

     layer.addSublayer(shapeLayer) 

    } 

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 
     super.touchesMoved(touches, with: event) 

     let touch = touches.first as! UITouch 
     let location = touch.location(in: self) 

     path.removeAllPoints() 
     path.move(to: startingPoint) 
     path.addLine(to: location) 

     shapeLayer.path = path.cgPath 

    } 

} 

最終結果

gif of the line endpoint moving on touch


更新:

タッチを離すと線が消えるようにするには、touchesEndedを使用します。このメソッドの内部では、パス上のポイントを削除してシェイプレイヤーに再割り当てするだけで、ビューが更新されます。

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    super.touchesEnded(touches, with: event) 
    path.removeAllPoints() 
    shapeLayer.path = path.cgPath 
} 
+1

ありがとうございます!偉大な説明 – skyguy

+0

私は質問があります - 私はそれが何もない(開始点と終了点が同じ点です)私はそれを私の指を離すと元に戻すでしょうか? – skyguy

+1

@skyguy上記の私の更新を参照してください。 – nathan

関連する問題