Skip to content

Commit

Permalink
Resume shimmering animation when application re-enters foreground
Browse files Browse the repository at this point in the history
  • Loading branch information
caiozullo committed Mar 20, 2024
1 parent 72c4c99 commit 18fc82f
Showing 1 changed file with 30 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,37 +15,43 @@ extension UIView {
}

get {
return layer.mask?.animation(forKey: shimmerAnimationKey) != nil
layer.mask is ShimmeringLayer
}
}

private var shimmerAnimationKey: String {
return "shimmer"
}

private func startShimmering() {
let white = UIColor.white.cgColor
let alpha = UIColor.white.withAlphaComponent(0.75).cgColor
let width = bounds.width
let height = bounds.height

let gradient = CAGradientLayer()
gradient.colors = [alpha, white, alpha]
gradient.startPoint = CGPoint(x: 0.0, y: 0.4)
gradient.endPoint = CGPoint(x: 1.0, y: 0.6)
gradient.locations = [0.4, 0.5, 0.6]
gradient.frame = CGRect(x: -width, y: 0, width: width*3, height: height)
layer.mask = gradient

let animation = CABasicAnimation(keyPath: #keyPath(CAGradientLayer.locations))
animation.fromValue = [0.0, 0.1, 0.2]
animation.toValue = [0.8, 0.9, 1.0]
animation.duration = 1.25
animation.repeatCount = .infinity
gradient.add(animation, forKey: shimmerAnimationKey)
layer.mask = ShimmeringLayer(size: bounds.size)
}

private func stopShimmering() {
layer.mask = nil
}

private class ShimmeringLayer: CAGradientLayer {
private var observer: Any?

convenience init(size: CGSize) {
self.init()

let white = UIColor.white.cgColor
let alpha = UIColor.white.withAlphaComponent(0.75).cgColor

colors = [alpha, white, alpha]
startPoint = CGPoint(x: 0.0, y: 0.4)
endPoint = CGPoint(x: 1.0, y: 0.6)
locations = [0.4, 0.5, 0.6]
frame = CGRect(x: -size.width, y: 0, width: size.width*3, height: size.height)

let animation = CABasicAnimation(keyPath: #keyPath(CAGradientLayer.locations))
animation.fromValue = [0.0, 0.1, 0.2]
animation.toValue = [0.8, 0.9, 1.0]
animation.duration = 1.25
animation.repeatCount = .infinity
add(animation, forKey: "shimmer")

observer = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { [weak self] _ in
self?.add(animation, forKey: "shimmer")
}
}
}
}

0 comments on commit 18fc82f

Please sign in to comment.