Skip to content

Instantly share code, notes, and snippets.

@mash3l777
Last active October 20, 2020 12:58
Show Gist options
  • Save mash3l777/af66a034c0e1569f78e8d928ad6ceb74 to your computer and use it in GitHub Desktop.
Save mash3l777/af66a034c0e1569f78e8d928ad6ceb74 to your computer and use it in GitHub Desktop.
GradientView for UIView Swift
import UIKit
@IBDesignable class GradientView: UIView {
private var gradientLayer: CAGradientLayer!
@IBInspectable var topColor: UIColor = .red {
didSet {
setNeedsLayout()
}
}
@IBInspectable var bottomColor: UIColor = .yellow {
didSet {
setNeedsLayout()
}
}
@IBInspectable var shadowColor: UIColor = .clear {
didSet {
setNeedsLayout()
}
}
@IBInspectable var shadowX: CGFloat = 0 {
didSet {
setNeedsLayout()
}
}
@IBInspectable var shadowY: CGFloat = -3 {
didSet {
setNeedsLayout()
}
}
@IBInspectable var shadowBlur: CGFloat = 3 {
didSet {
setNeedsLayout()
}
}
@IBInspectable var startPointX: CGFloat = 0 {
didSet {
setNeedsLayout()
}
}
@IBInspectable var startPointY: CGFloat = 0.5 {
didSet {
setNeedsLayout()
}
}
@IBInspectable var endPointX: CGFloat = 1 {
didSet {
setNeedsLayout()
}
}
@IBInspectable var endPointY: CGFloat = 0.5 {
didSet {
setNeedsLayout()
}
}
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
setNeedsLayout()
}
}
override class var layerClass: AnyClass {
return CAGradientLayer.self
}
override func layoutSubviews() {
self.gradientLayer = self.layer as? CAGradientLayer
self.gradientLayer.colors = [topColor.cgColor, bottomColor.cgColor]
self.gradientLayer.startPoint = CGPoint(x: startPointX, y: startPointY)
self.gradientLayer.endPoint = CGPoint(x: endPointX, y: endPointY)
self.layer.cornerRadius = cornerRadius
self.layer.shadowColor = shadowColor.cgColor
self.layer.shadowOffset = CGSize(width: shadowX, height: shadowY)
self.layer.shadowRadius = shadowBlur
self.layer.shadowOpacity = 1
}
func animate(duration: TimeInterval, newTopColor: UIColor, newBottomColor: UIColor) {
let fromColors = self.gradientLayer?.colors
let toColors: [AnyObject] = [ newTopColor.cgColor, newBottomColor.cgColor]
self.gradientLayer?.colors = toColors
let animation : CABasicAnimation = CABasicAnimation(keyPath: "colors")
animation.fromValue = fromColors
animation.toValue = toColors
animation.duration = duration
animation.isRemovedOnCompletion = true
animation.fillMode = kCAFillModeForwards
animation.timingFunction = CAMediaTimingFunction(name: kCAFilterLinear)
self.gradientLayer?.add(animation, forKey:"animateGradient")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment