The code below creates a "shimmer" effect and works great. (The look of reflected light moving across a glossy surface.) It's currently set to repeat forever which is fine, however, I'd like there to be a pause between each shimmer. I can delay the start of the effect, but I can't seem to figure out how to delay each run. Bonus points if the delay time is random.
func startShimmering() {
let light = UIColor.white.cgColor
let alpha = UIColor.white.withAlphaComponent(0.0).cgColor
let gradient = CAGradientLayer()
gradient.colors = [alpha, light, alpha]
gradient.frame = CGRect(x: -self.bounds.size.width, y: 0, width: 3 * self.bounds.size.width, height: self.bounds.size.height)
gradient.startPoint = CGPoint(x: 1.0, y: 0.525)
gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
gradient.locations = [0.1, 0.5, 0.9]
self.layer.mask = gradient
let animation = CABasicAnimation(keyPath: "locations")
animation.fromValue = [0.0, 0.1, 0.2]
animation.toValue = [0.8, 0.9, 1.0]
animation.duration = 1.5
animation.repeatCount = HUGE
gradient.add(animation, forKey: "shimmer")
}
As mentioned in Kevin's answer, you can use a
CAAnimationGroup
to add a delay to the end of your shimmer animation.The "shimmer" animation will have a duration longer than the group's animation. Any difference between these two durations will be the delay between animations.
Here is the code to do so, ready for a Swift Playground:
Here is the end result:
(The gif animates the shimmer three times, which is why every third "shimmer" the delay is shorter.)