在 Swift 4 中移动 UIBezierPath 笔划的最佳方法是什么?

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

我正在尝试实现一个可以使用 UIBezierPath 笔划在 Swift 4 中更改位置的光标。目前,我有一个函数,其参数位置包含 'cursor' 的新 x 和 y 位置。我想将此位置参数用作 UIView 中光标的新位置。每次调用该函数时,我当前的实现都会呈现另一个光标。有没有办法改变 UIBezierPath 的一个实例的位置?请参阅下面的示例代码以供参考。

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

您可以从 0,0 开始创建贝塞尔曲线路径,然后在绘制之前将 x/y 平移变换应用于绘图上下文。详细信息取决于您的绘图方式(您发布的代码是从视图的 draw(rect:) 方法调用的吗?)

将光标绘制为 CAShapeLayer 对象。这使您无需重新绘制即可移动光标。

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