Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchellporter/2afb59157d29e4f2c666db8e911d598b to your computer and use it in GitHub Desktop.
Save mitchellporter/2afb59157d29e4f2c666db8e911d598b 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