Created
February 21, 2018 16:41
-
-
Save jakemor/43c311be167a1797e55f1e537b870c52 to your computer and use it in GitHub Desktop.
Simple gradients for UIViews in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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