swift渐变色

本文内容来源于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
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • //创建渐变色层 let gradient:CAGradientLayer = CAGradientLayer()...
    旅途开发者阅读 2,036评论 0 1
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,262评论 4 61
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,830评论 25 709
  • (聽說,進去的人沒回來過) (你覺得頭痛,忘記了一切,只記得你姐姐三年前掉下來,突然一陣頭痛,你忘記後面了) (咦...
    小雞魔人阅读 71评论 0 0
  • 夏日正炎,我搬来藤椅坐在家门外的湖边,乘着树荫,好不惬意。蝉鸣一声比一声响,我都要觉得那只蝉要比太阳大了。啊,夏天...
    瞎掰少女阅读 208评论 0 0