Created
January 30, 2019 13:35
-
-
Save darrarski/5195675d73fbba841cf19f2221b1e902 to your computer and use it in GitHub Desktop.
Simple UIKit gradient view
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
import UIKit | |
class GradientView: UIView { | |
init(style: GradientStyle) { | |
super.init(frame: .zero) | |
isUserInteractionEnabled = false | |
gradientLayer.colors = style.colors.map { $0.color.cgColor } | |
gradientLayer.locations = style.colors.map { NSNumber(value: $0.location) } | |
gradientLayer.startPoint = style.direction.startPoint | |
gradientLayer.endPoint = style.direction.endPoint | |
layer.addSublayer(gradientLayer) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
return nil | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
gradientLayer.frame = layer.bounds | |
} | |
private let gradientLayer = CAGradientLayer() | |
} | |
struct GradientStyle { | |
let colors: [GradientColor] | |
let direction: GradientDirection | |
} | |
struct GradientColor { | |
let location: Float | |
let color: UIColor | |
} | |
struct GradientDirection { | |
let startPoint: CGPoint | |
let endPoint: CGPoint | |
} | |
extension GradientDirection { | |
static var horizontal: GradientDirection { | |
return GradientDirection( | |
startPoint: CGPoint(x: 0, y: 0.5), | |
endPoint: CGPoint(x: 1, y: 0.5) | |
) | |
} | |
static var vertical: GradientDirection { | |
return GradientDirection( | |
startPoint: CGPoint(x: 0.5, y: 0), | |
endPoint: CGPoint(x: 0.5, y: 1) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment