Swift UIView:让路径始终在人的手指末端?

时间:2017-05-14 01:07:28

标签: ios swift swift3 cashapelayer

好的,我是UIBezierPaths的新手,但我需要有一条路径,根据用户手指的位置更新端点。它应该在touchesMoved

中更改

到目前为止,我有:

func customInit() {
    print("init scene")
    self.backgroundColor = UIColor.cyan

    path.move(to: CGPoint(x: 0, y: 0))
    path.addLine(to: CGPoint(x: 300, y: 300))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.blue.cgColor
    shapeLayer.lineWidth = 3.0

    self.layer.addSublayer(shapeLayer)
}

override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    var touch : UITouch! =  touches.first! as UITouch
    var location = touch.location(in: self)

    path.move(to: location)
}

我认为这会更新路径端点,但除了绘制原始线之外没有任何事情发生。我不想使用SKScene,但不知道出了什么问题。

如何让一条线在用户点击时始终有一个点?

1 个答案:

答案 0 :(得分:2)

你非常接近!你只缺少一些东西。

调用touchesMoved时,您需要更新路径并将其重新分配给CAShapeLayer,以便可以重新绘制它。现在你只是对路径对象进行了修改,但没有重新绘制它。

最终代码

class DrawingView: UIView {

    let startingPoint = CGPoint(x: 0, y: 0)

    let shapeLayer = CAShapeLayer()
    let path = UIBezierPath()

    override init(frame: CGRect) {
        super.init(frame: frame)
        customInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        customInit()
    }

    func customInit() {

        backgroundColor = UIColor.cyan

        path.move(to: startingPoint)
        path.addLine(to: CGPoint(x: 50, y: 50))

        shapeLayer.path = path.cgPath
        shapeLayer.strokeColor = UIColor.blue.cgColor
        shapeLayer.lineWidth = 3.0

        layer.addSublayer(shapeLayer)

    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)

        let touch =  touches.first as! UITouch
        let location = touch.location(in: self)

        path.removeAllPoints()
        path.move(to: startingPoint)
        path.addLine(to: location)

        shapeLayer.path = path.cgPath

    }

}

最终结果

gif of the line endpoint moving on touch

(在Xcode 8.3.2游乐场测试)

<强>更新

要在触摸释放时使线条消失,请使用touchesEnded。在此方法中,只需删除路径上的点并将其重新分配给shapeLayer,以便更新视图。

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
    path.removeAllPoints()
    shapeLayer.path = path.cgPath
}