2023-11-14|閱讀時間 ‧ 約 24 分鐘

[iOS][swift]UILabel字體顏色漸層


extension UILabel{
func GradientLabel(_ colors: [Any]? , isVertical : Bool, locations: [NSNumber]? = [0.0, 1.0]) {
for sub:UIView in self.subviews {
if sub.tag == 2 {
sub.removeFromSuperview()
}
}

let containerView = UIView.init(frame: self.bounds)
containerView.tag = 2
self.addSubview(containerView)

let label = UILabel.init(frame: self.bounds)
label.text = self.text
label.font = self.font
label.textAlignment = self.textAlignment
containerView.addSubview(label)

let gradientLayer = CAGradientLayer()
gradientLayer.colors = colors
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = isVertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)
gradientLayer.locations = locations//[0.0, 1.0]
gradientLayer.frame = label.frame
containerView.layer.insertSublayer(gradientLayer, at: 0)
gradientLayer.mask = label.layer

}
}



分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.