2017-09-14 67 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 :)方法。 –