I need create line animation with constant length along rounded rectangle.
So I stopped after creating needed BezierPath UIBezierPath(roundedRect: CGRect(x: 50, y: 50, width: 100, height: 100), cornerRadius: 5)
so next step what I need to do is to use CAKeyframeAnimation
for animating line with width 45 along that path
Does someone could help me with that?
Asked
Active
Viewed 212 times
0

YuraTR
- 11
- 2
-
Do you want to animate the line drawing from start to end? – RajeshKumar R Jun 11 '19 at 08:02
-
yes @RajeshKumarR, but problem is that line is 1/4 length of that path. Plus I need infinity repeated count – YuraTR Jun 11 '19 at 08:14
-
1bet you will find answer here - https://stackoverflow.com/questions/42978418/draw-line-animated – Kirow Jun 11 '19 at 09:10
-
@Kirow I am using `CAKeyframeAnimation(keyPath: "strokeEnd")` and `CAKeyframeAnimation(keyPath: "strokeStart")`. The main problem is that it's not looks like infinity its stopped when `strokeEnd = 0` because its could not be grater than 1 – YuraTR Jun 11 '19 at 09:25
1 Answers
1
Ok, then. Use dash pattern instead of start/end. Suggest to use this repo to calculate cgPath length to make pattern you need.
let rectangle = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
rectangle.clipsToBounds = true
rectangle.backgroundColor = .blue
rectangle.layer.cornerRadius = 50
let path = UIBezierPath(roundedRect: rectangle.bounds, cornerRadius: 50)
let shape = CAShapeLayer()
shape.path = path.cgPath
shape.lineWidth = 10
shape.strokeColor = UIColor.red.cgColor
shape.fillColor = UIColor.clear.cgColor
let length = path.cgPath.length
shape.lineDashPattern = [NSNumber(value: 45), NSNumber(value: Float(length - 45))]
rectangle.layer.addSublayer(shape)
let animation = CABasicAnimation(keyPath: "lineDashPhase")
animation.fromValue = 0
animation.toValue = length //-length to run animation clock-wise
animation.repeatCount = .infinity
animation.duration = 10
shape.add(animation, forKey: "MyAnimation")
PlaygroundPage.current.liveView = rectangle

Kirow
- 1,077
- 12
- 25