Is it possible to reposition an already drawn CGPath/UIBezierPath on a view? I would like to move or change a path\'s position then perhaps recall the drawinRect method to just
I did it a bit different from other answers above.
Let's suppose you want to move a circle, first I define its center coordinates and radius in global variables, like this:
var center: CGPoint = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height/2)
var radius: CGFloat = 10
I draw this circle like in the code bellow:
override func draw(_ rect: CGRect) {
super.draw(rect)
drawCircle()
}
func drawCircle() {
let circle = UIBezierPath(
arcCenter: self.center,
radius: CGFloat(self.radius),
startAngle: CGFloat(0),
endAngle: CGFloat(2*Double.pi),
clockwise: true)
let circleLayer = CAShapeLayer()
circleLayer.path = circle.cgPath
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.strokeColor = UIColor.black.cgColor
circleLayer.lineWidth = 10.0
layer.addSublayer(circleLayer)
}
Inside the UIView, I have a touchesMoved(), like this:
override func touchesMoved(_ touches: Set, with event: UIEvent?){
if let touch = touches.first {
let pos = touch.location(in: self)
if (pow(pos.x-self.center.x,2) + pow(pos.y-self.center.y,2) <= pow(self.radius,2)){
self.center = CGPoint(x: pos.x, y: pos.y)
}
setNeedsDisplay()
}
}
Everytime the touch is inside the circle, its center coordinates are updated and the UIView is redrawn with setNeedDisplay()
, so the circle moves.
Hope it helps someone!