美文网首页
swift 文字渐变色

swift 文字渐变色

作者: 你是真的很皮 | 来源:发表于2021-08-26 11:22 被阅读0次
2017082720150929288.png

class ViewController: UIViewController {
     
    //文本标签
    @IBOutlet weak var label: UILabel!
     
    //文本标签背景
    @IBOutlet weak var labelBg: UIView!
     
    //渐变层
    var gradientLayer:CAGradientLayer!
     
     
    override func viewDidLoad() {
        super.viewDidLoad()
         
        //将主视图背景设置为灰色
        self.view.backgroundColor = UIColor.darkGray
         
        //创建CAGradientLayer对象
        self.gradientLayer = CAGradientLayer()
         
        //设置初始渐变色
        self.gradientLayer.colors = [UIColor.black.cgColor,
                                     UIColor.white.cgColor,
                                     UIColor.black.cgColor]
         
        //设置每种颜色初始所在的位置
        self.gradientLayer.locations = [0, 0, 0.25]
         
        //设置渲染的起始结束位置(横向渐变)
        self.gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        self.gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
         
        //设置其CAGradientLayer对象的frame,并插入view的layer
        self.gradientLayer.frame = CGRect(x: 0, y: 0,
                                          width: labelBg.frame.size.width,
                                          height: labelBg.frame.size.height)
         
        //将渐变层添加到文本标签背景上
        self.labelBg.layer.insertSublayer(gradientLayer, at: 0)
         
        //添加渐变动画(让白色光泽从左向右移动)
        let gradientAnimation = CABasicAnimation(keyPath: "locations")
        gradientAnimation.fromValue = [0, 0, 0.2]
        gradientAnimation.toValue = [0.8, 1, 1]
        gradientAnimation.duration = 12.5
        //动画一致重复执行
        gradientAnimation.repeatCount = HUGE
        self.gradientLayer.add(gradientAnimation, forKey: nil)
         
        //设置遮罩,让渐变层透过文字显示出来
        self.labelBg.mask = self.label
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

[标题]参考:https://www.hangge.com/blog/cache/detail_1769.html

相关文章

网友评论

      本文标题:swift 文字渐变色

      本文链接:https://www.haomeiwen.com/subject/zcayiltx.html