CAGradientLayer是用来生成两种或更多颜色平滑渐变的。用Core Graphics复制一个CAGradientLayer并将内容绘制到一个普通图层的寄宿图也是有可能的,但是CAGradientLayer的真正好处在于绘制使用了硬件加速。
基础属性
- colors 颜色数组 :CGColorRef对象的数组定义每个渐变的颜色停止。默认为零。可以做成动画。
- locations 位置数组 :一个可选的每个组NSNumber对象定义的位置梯度停止的价值区间[0,1]。的值必须单调递增。如果一个空数组,停止假设均匀分布在[0,1]区间。当呈现,之前的颜色映射到输出色彩内插。默认为零。可以做成动画。
- startpoint,endpoint:设置起始点和终点就不需要设置locations,反之同样,开始点和结束点的梯度当卷入层的协调空间。起点对应于第一个梯度站,终点到最后梯度停止。这两个点是定义在一个坐标空间,然后映射到单位层的边界矩形时。(即左下角(0,0)角落的层,[1]是右上角)。默认值[。5、0]和[。5,分别1]。都可以做成动画。
基础渐变(2种颜色)
let gradientLayer = CAGradientLayer()//梯度层:设置颜色梯度
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override init (style: UITableViewCellStyle, reuseIdentifier : String?){
super.init(style: style, reuseIdentifier: reuseIdentifier)
gradientLayer.frame = self.bounds
let color1 = UIColor(white: 1.0, alpha: 0.2).CGColor as CGColorRef
let color2 = UIColor(white: 1.0, alpha: 0.1).CGColor as CGColorRef
let color3 = UIColor.clearColor().CGColor as CGColorRef
let color4 = UIColor(white: 0.0, alpha: 0.05).CGColor as CGColorRef
gradientLayer.colors = [color1,color2,color3,color4]
gradientLayer.locations = [0,0.04,0.95,1.0]
layer.insertSublayer(gradientLayer, atIndex: 0)
}
override func layoutSubviews() {
super.layoutSubviews()
gradientLayer.frame = self.frame
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//因为对每个单元格都设置梯度所以渐变是一单元格为单位
多重渐变
let gradientLayer = CAGradientLayer()
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
gradientLayer.frame = self.bounds
let color1 = UIColor(red: 1, green: 0, blue: 0, alpha:1).CGColor as CGColorRef
let color2 = UIColor(red: 0, green: 1, blue: 0, alpha:1).CGColor as CGColorRef
let color3 = UIColor(red: 0, green: 0, blue: 1, alpha:1).CGColor as CGColorRef
gradientLayer.colors = [color1, color2, color3]
gradientLayer.locations = [0.10, 0.50, 0.90]
layer.insertSublayer(gradientLayer, atIndex: 0)
}
override func layoutSubviews() {
super.layoutSubviews()
gradientLayer.frame = self.bounds
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}