我正在尝试将彩虹般的闪光动画应用于 UILabel 但不知道从哪里开始,我已设法将彩虹渐变颜色应用于 UILabel 但动画部分仍然存在。请帮助我们在以下链接中实现结果:-
以下是我尝试过的代码:-
let hueColors = stride(from: 0, to: 1, by: 0.1).map({ UIColor(hue: $0, saturation: 1, brightness: 1, alpha: 1.0).cgColor })
override func viewDidLoad() {
super.viewDidLoad()
self.lblDisplayTitleRecommendedWallet.text = "Recommended Wallet".localized
self.lblDisplayTitleRecommendedWallet.gradientColors = self.hueColors
}
class GradientLabel: UILabel {
var gradientColors: [CGColor] = []
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: nil) 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)
}
}