2017-09-14 4 views
1

私はUIBezierPathを使って線を描画します。私はそれを伸ばすが、それは動作しません。私は間違って何をしていますか?行の開始点と終了点を変更するにはどうすればよいですか?UIBezierPathを使用して描画される線を引き伸ばす方法は?

let line = CAShapeLayer() 
let linePath = UIBezierPath() 

func DrawLine() 
{ 
    linePath.move(to: to: CGPoint(x: 100, y: 100) 
    linePath.addLine(to: CGPoint(x: self.view.frame.width - 100, y: 100)) 
    line.path = linePath.cgPath 
    line.strokeColor = UIColor.red.cgColor 
    line.lineWidth = 1 
    line.lineJoin = kCALineJoinRound 
    self.view.layer.addSublayer(line) 
} 
override func viewDidLoad() 
{   
    super.viewDidLoad() 
    DrawLine() 
} 
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
{ 
    line.frame.origin.x -=10 
    line.frame.size.width += 10 
} 

答えて

0

プロパティを使用して、変更するポイントを保存し、必要に応じてパスを再作成してみてください。

class FileViewController: UIViewController { 
    let line = CAShapeLayer() 
    var point1 = CGPoint.zero 
    var point2 = CGPoint.zero 

    func DrawLine() { 
     point1 = CGPoint(x: 100, y: 100) 
     point2 = CGPoint(x: self.view.frame.width - 100, y: 100) 

     let linePath = UIBezierPath() 
     linePath.move(to: point1) 
     linePath.addLine(to: point2) 

     line.path = linePath.cgPath 
     line.strokeColor = UIColor.red.cgColor 
     line.lineWidth = 1 
     line.lineJoin = kCALineJoinRound 
     self.view.layer.addSublayer(line) 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     DrawLine() 
    } 

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
     point1.x -= 10 
     point2.x += 10 

     let linePath = UIBezierPath() 
     linePath.move(to: point1) 
     linePath.addLine(to: point2) 

     line.path = linePath.cgPath 
    } 
} 
+0

touchesBeganメソッドは、ビューをタッチするとトリガーされます。ポイント1とポイント2は10ポイント変更され、パスはそれらの新しいポイントで再現されます。 CAShapeLayerのパスが更新されます。 –

+0

プロパティ値を変更すると、CALayersが自動的に更新されます。この場合、パスのプロパティを変更しています。 setNeedsDisplayは必要ではなく、CALayerにdraw(rect :)メソッドはありません。ただし、レイヤーをサブクラス化する場合は、drawメソッドをオーバーライドできます。 –

関連する問題