Created
January 11, 2021 22:06
-
-
Save SergLam/1f49d05fe1dc042e1e9d88537f9413a3 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
Very good solution, thank you so much 🚀