美文网首页
swift渐变色

swift渐变色

作者: henu_Larva | 来源:发表于2017-12-27 10:45 被阅读25次

    本文内容来源于http://www.hangge.com/,仅作学习记录...
    需求:视图由上至下出现渐变色,点击视图更换另一组颜色,有过渡动画效果。
    代码如下,有注释

    import UIKit
    
    class ViewController: UIViewController,CAAnimationDelegate {
        
        //渐变色
        let colorsSet = [
            [UIColor.yellow.cgColor,UIColor.orange.cgColor],
            [UIColor.cyan.cgColor,UIColor.green.cgColor],
            [UIColor.magenta.cgColor,UIColor.blue.cgColor]
        ]
        
        //当前渐变色索引
        var currentIndex = 0
        
        var gradientLayer : CAGradientLayer!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            
            //监听单击事件,每单击一次就切换一组渐变色
            let tapSingle = UITapGestureRecognizer(target:self,action:#selector(tapSingleDid))
            tapSingle.numberOfTapsRequired = 1
            tapSingle.numberOfTouchesRequired = 1
            self.view .addGestureRecognizer(tapSingle)
            
            //初始化CAGradientLayer对象
            gradientLayer = CAGradientLayer()
            gradientLayer.colors = colorsSet.first
            gradientLayer.locations = [0.0,1.0]
            
            gradientLayer.frame = self.view.bounds
            self.view.layer.insertSublayer(gradientLayer, at: 0)
        }
        
        @objc func tapSingleDid() {
            var nextIndex = currentIndex + 1
            if nextIndex >= colorsSet.count {
                nextIndex = 0
            }
            
            //添加渐变色动画
            let colorChangeAnimation = CABasicAnimation(keyPath:"colors") //keyPath 小写 k
            colorChangeAnimation.delegate = self
            colorChangeAnimation.duration = 2.0
            colorChangeAnimation.fromValue = colorsSet[currentIndex]
            colorChangeAnimation.toValue = colorsSet[nextIndex]
            colorChangeAnimation.fillMode = kCAFillModeForwards
            //动画结束后保持最终的效果
            colorChangeAnimation.isRemovedOnCompletion = false;
            gradientLayer.add(colorChangeAnimation, forKey: "colors")
            
            currentIndex = nextIndex
        }
    }
    

    相关文章

      网友评论

          本文标题:swift渐变色

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