Created
November 1, 2022 07:53
-
-
Save abhi21git/cd88d32187e0d9ec64d3ab49439bba2e to your computer and use it in GitHub Desktop.
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
class GradientTextLabel: UILabel { | |
var gradientColors: [CGColor] = [UIColor.orangeRed.cgColor, UIColor.brightRed.cgColor, UIColor.warmPurple.cgColor, UIColor.darkishBlue.cgColor] | |
var locations: [CGFloat]? = [0.0, 0.25, 0.5, 0.75] | |
override func drawText(in rect: CGRect) { | |
if let gradientColor = drawGradientColor(in: rect, colors: gradientColors) { | |
self.textColor = gradientColor | |
} | |
super.drawText(in: rect) | |
} | |
private func drawGradientColor(in rect: CGRect, colors: [CGColor]) -> UIColor? { | |
let currentContext = UIGraphicsGetCurrentContext() | |
currentContext?.saveGState() | |
defer { currentContext?.restoreGState() } | |
let size = rect.size | |
UIGraphicsBeginImageContextWithOptions(size, false, 0) | |
guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), | |
colors: colors as CFArray, | |
locations: locations) else { return nil } | |
let context = UIGraphicsGetCurrentContext() | |
context?.drawLinearGradient(gradient, | |
start: CGPoint.zero, | |
end: CGPoint(x: size.width, y: 0), | |
options: []) | |
let gradientImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
guard let image = gradientImage else { return nil } | |
return UIColor(patternImage: image) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment