-
-
Save karosLi/35e1b89f07ec34f3d62ae52813c71672 to your computer and use it in GitHub Desktop.
Gradient Label for iOS in Swift
This file contains hidden or 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 | |
final class GradientLabel: UILabel { | |
private var colors: [UIColor] = [.supAzure, .supAppleFive] | |
private var startPoint: CGPoint = CGPoint(x: 0.0, y: 0.5) | |
private var endPoint: CGPoint = CGPoint(x: 1.0, y: 0.5) | |
private var textColorLayer: CAGradientLayer = CAGradientLayer() | |
// MARK: - Life cycle | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
setup() | |
} | |
required init?(coder: NSCoder) { | |
super.init(coder: coder) | |
setup() | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
applyColors() | |
} | |
// MARK: - Public functions | |
func update(colors: [UIColor], startPoint: CGPoint, endPoint: CGPoint) { | |
self.colors = colors | |
self.startPoint = startPoint | |
self.endPoint = endPoint | |
applyColors() | |
} | |
// MARK: - Private functions | |
private func setup() { | |
isAccessibilityElement = true | |
applyColors() | |
} | |
private func applyColors() { | |
let gradient = getGradientLayer(bounds: self.bounds) | |
textColor = gradientColor(bounds: self.bounds, gradientLayer: gradient) | |
} | |
private func getGradientLayer(bounds: CGRect) -> CAGradientLayer { | |
textColorLayer.frame = bounds | |
textColorLayer.colors = colors.map{ $0.cgColor } | |
textColorLayer.startPoint = startPoint | |
textColorLayer.endPoint = endPoint | |
return textColorLayer | |
} | |
} |
This file contains hidden or 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 | |
extension UIView { | |
func gradientColor(bounds: CGRect, gradientLayer: CAGradientLayer) -> UIColor? { | |
UIGraphicsBeginImageContext(gradientLayer.bounds.size) | |
guard let context = UIGraphicsGetCurrentContext() else { | |
return nil | |
} | |
gradientLayer.render(in: context) | |
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { | |
return nil | |
} | |
UIGraphicsEndImageContext() | |
return UIColor(patternImage: image) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment