工具类方法
extension UILabel {
func setGradientTextColor(startColor: UIColor, endColor: UIColor, startPoint: CGPoint, endPoint: CGPoint) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
gradientLayer.startPoint = startPoint
gradientLayer.endPoint = endPoint
let renderer = UIGraphicsImageRenderer(size: gradientLayer.bounds.size)
let gradientImage = renderer.image { context in
gradientLayer.render(in: context.cgContext)
}
textColor = UIColor(patternImage: gradientImage)
}
}
使用
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
label.text = "Hello, World!"
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 20)
label.setGradientTextColor(startColor: .red,
endColor: .blue,
startPoint: CGPoint(x: 0, y: 0),
endPoint: CGPoint(x: 0, y: 1))
view.addSubview(label)
}
}