Skip to content

Instantly share code, notes, and snippets.

@jakemor
Created February 21, 2018 16:41
Show Gist options
  • Save jakemor/43c311be167a1797e55f1e537b870c52 to your computer and use it in GitHub Desktop.
Save jakemor/43c311be167a1797e55f1e537b870c52 to your computer and use it in GitHub Desktop.
Simple gradients for UIViews in Swift
// MARK: - Usage
//
// view.setBackgroundGradient(start: .red, end: .blue, type: .topRightBottomLeft)
//
// MARK: - UIView+Gradient
extension UIView {
typealias GradientPoint = (x: CGPoint, y: CGPoint)
enum GradientType {
case leftRight
case rightLeft
case topBottom
case bottomTop
case topLeftBottomRight
case bottomRightTopLeft
case topRightBottomLeft
case bottomLeftTopRight
var gradientPoint: GradientPoint {
get {
switch self {
case .leftRight:
return (x: CGPoint(x: 0, y: 0.5), y: CGPoint(x: 1, y: 0.5))
case .rightLeft:
return (x: CGPoint(x: 1, y: 0.5), y: CGPoint(x: 0, y: 0.5))
case .topBottom:
return (x: CGPoint(x: 0.5, y: 0), y: CGPoint(x: 0.5, y: 1))
case .bottomTop:
return (x: CGPoint(x: 0.5, y: 1), y: CGPoint(x: 0.5, y: 0))
case .topLeftBottomRight:
return (x: CGPoint(x: 0, y: 0), y: CGPoint(x: 1, y: 1))
case .bottomRightTopLeft:
return (x: CGPoint(x: 1, y: 1), y: CGPoint(x: 0, y: 0))
case .topRightBottomLeft:
return (x: CGPoint(x: 1, y: 0), y: CGPoint(x: 0, y: 1))
case .bottomLeftTopRight:
return (x: CGPoint(x: 0, y: 1), y: CGPoint(x: 1, y: 0))
}
}
}
}
func setBackgroundGradient(start: UIColor, end: UIColor, type: GradientType) {
let gradientPoint = type.gradientPoint
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.bounds
gradientLayer.startPoint = gradientPoint.x
gradientLayer.endPoint = gradientPoint.y
gradientLayer.colors = [start.cgColor, end.cgColor]
self.layer.addSublayer(gradientLayer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment