简体   繁体   中英

How to stretch a line which is drawn using UIBezierPath?

I draw a line using UIBezierPath. I want to stretch it but it doesn't work. What am I doing wrong? How can I change start and end point of the line?

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
}

Try using properties to store the points you want to change and recreate the path when needed.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM