Search code examples
iosswiftipadcore-graphicsswift4

What's the best way to move a UIBezierPath stroke in Swift 4?


I am trying to implement a cursor that can change position in Swift 4 using UIBezierPath stroke. Currently, I have a function that has a parameter location which contains the new x and y position of the 'cursor'. I'd like to use this location parameter as the new position of the cursor in the UIView. My currently implementation renders another cursor each time the function is called. Is there a way to change the position of one instance of a UIBezierPath? See example code below for reference.

private var cursor:UIBezierPath = UIBezierPath()

public func changeCursorLocation(location: ScreenCoordinates) {
    self.cursor = UIBezierPath()

    UIColor.black.setStroke()
    self.cursor.lineWidth = 2

    self.cursor.move(to: CGPoint(x: location.x, y: location.y))
    self.cursor.addLine(to: CGPoint(x: location.x + 100, y: location.y)) // change if staff space changes
    self.cursor.stroke()
}

Solution

  • Draw the cursor as CAShapeLayer object. This lets you move the cursor without having to redraw it.

    class MyView: UIView {
        let cursor = CAShapeLayer()
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setup()
        }
    
        func setup() {
            // Draw cursor and add it to this view's layer
            let path = UIBezierPath()
            path.move(to: .zero)
            path.addLine(to: CGPoint(x: 100, y: 0))
    
            cursor.path = path.cgPath
            cursor.strokeColor = UIColor.black.cgColor
            cursor.lineWidth = 2
    
            layer.addSublayer(cursor)
    
            changeCursorLocation(location: CGPoint(x: 50, y: 100))
        }
    
        func changeCursorLocation(location: CGPoint) {
            cursor.position = location
        }
    }
    

    enter image description here