I am trying to add spinner effect to a circular view.
func spin() {
let circlePathLayer = CAShapeLayer()
circlePathLayer.fillColor = nil
circlePathLayer.strokeColor = UIColor.redColor.cgColor
circlePathLayer.lineWidth = 6
layer.addSublayer(circlePathLayer)
setPath(to: circlePathLayer)
animate(layer: circlePathLayer)
}
private func setPath(to layer: CAShapeLayer) {
layer.path = UIBezierPath(ovalIn: bounds.insetBy(dx: layer.lineWidth / 2,
dy: layer.lineWidth / 2)).cgPath
}
private func animate(layer: CAShapeLayer) {
animateKeyPath(keyPath: "strokeEnd",
duration: 1,
values: [0, 1],
layer: layer)
animateKeyPath(keyPath: "strokeStart",
duration: 1,
values: [(0 - 0.1) as CGFloat, (1 - 0.1) as CGFloat],
layer: layer)
}
private func animateKeyPath(keyPath: String, duration: CFTimeInterval, values: [CGFloat], layer: CAShapeLayer) {
let animation = CAKeyframeAnimation(keyPath: keyPath)
animation.values = values
animation.calculationMode = .linear
animation.duration = duration
animation.repeatCount = Float.infinity
layer.add(animation, forKey: animation.keyPath)
}
But for the above code, at the end of animation duration
, a flicker happens every time at 1
position of the strokeEnd
. How could I overcome the flicker and regulate the spinner?
Just to notice the effect visually, I have set the duration to 5 seconds. Please notice when the spinner reaches 3'o clock position.