Swift UIView: make path always end of finger?
OK, I'm new to UIBezierPaths, but I need a path that updates the endpoint to match where the user's finger is. He must change intotouchesMoved
So far I have:
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)
}
I thought this would update the endpoint of the path, but nothing happens outside of drawing the original line. I would hate to use SKScene for this, but I donβt know whatβs going wrong.
How can I make the string always have a dot at the user's point?
source to share
You are very close! There are just a few things missing.
When called touchesMoved
, you need to update the path and reassign it to CAShapeLayer
so that it can be redrawn. For now, you are just making changes to the path object, but not redrawing it.
Final code
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
}
}
Final result
(tested on playground Xcode 8.3.2)
Update:
To make the line disappear when you release the touch, use touchesEnded
. Inside this method, just remove the points in the path and reassign it to the shapeLayer to update the view.
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
path.removeAllPoints()
shapeLayer.path = path.cgPath
}
source to share