2017-09-14 66 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正被修改10pts和路徑重新創建這些新的點。然後更新CAShapeLayer的路徑。 –

+0

當您更改屬性值時,CALayers會自動更新。在這種情況下,我們正在改變路徑屬性。 setNeedsDisplay不是必需的,CALayer中沒有draw(rect :)方法。儘管如果你繼承這個圖層,你可以重寫draw(in :)方法。 –