Skip to content

Instantly share code, notes, and snippets.

@antonio081014
Created March 1, 2022 17:31
Show Gist options
  • Save antonio081014/5f63a20c7c77c7b4110eec32f357f29e to your computer and use it in GitHub Desktop.
Save antonio081014/5f63a20c7c77c7b4110eec32f357f29e to your computer and use it in GitHub Desktop.
Shimmering Effect for UIView
import UIKit
extension UIView {
public var isShimmering: Bool {
get {
return layer.mask?.animation(forKey: shimmerAnimationKey) != nil
}
set {
if newValue {
startShimmering()
} else {
stopShimmering()
}
}
}
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)
}
private func stopShimmering() {
layer.mask = nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment