颜色线性渐变-CAGradientLayer

我们先来看一下效果图吧:

其实,就是一个颜色的线性渐变,使用CAGradientLayer很容易就能实现。由于代码很简单,就不做过多讲解了,直接看代码吧。

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4     
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         setupBackgroundLayer()
 8     }
 9     
10     private func setupBackgroundLayer(){
11         // 线性渐变图层
12         let layer:CAGradientLayer = CAGradientLayer()
13         
14         // layer是通过bounds和position来指定位置的
15         layer.bounds = view.bounds
16         layer.position = view.center
17         
18         // 设置背景颜色
19         // layer.backgroundColor = UIColor.red.cgColor
20         // 设置渐变颜色数组
21         let color1 = UIColor.red.cgColor
22         let color2 = UIColor.blue.cgColor
23         let color3 = UIColor.orange.cgColor
24         layer.colors = [color1,color2,color3]
25         
26         // 设置颜色的位置数组
27         layer.locations = [0, 0.6,1.0]
28         
29         // 将图层插入到最底部
30         view.layer.insertSublayer(layer, at: 0)
31     }
32 }
原文地址:https://www.cnblogs.com/panda1024/p/6240843.html