通過 CAGradientLayer 可以很容易實現漸變色效果,而且這個漸變色的效果可以拿來做動畫。
一開始的背景圖就是用了漸變效果,而當點下按鈕以後,配合 CABasicAnimation 做漸變色切換的動畫。
給 CAGradientLayer 設定參數,startPoint / endPoint 決定了漸變的方向,左上角座標為 {0,0} 右下角座標為 {1,1},色彩組 colors
gradientLayer = CAGradientLayer()
gradientLayer.frame = view.bounds
gradientLayer.colors = [
UIColor(red: 42/255, green: 147/255, blue: 212/255, alpha: 1.0).cgColor,
UIColor(red: 240/255, green: 105/255, blue: 102/255, alpha: 1.0).cgColor
]
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
view.layer.addSublayer(gradientLayer)
先建立色彩組,用來切換色彩。
var gradientSet = [[CGColor]]()
var currentGradient:Int = 0
let colorOne = UIColor(red: 247/255, green: 0, blue: 68.255, alpha: 1.0).cgColor
let colorTwo = UIColor(red: 246/255, green: 214/255, blue: 0, alpha: 1.0).cgColor
let colorThree = UIColor(red: 17/205, green: 205/255, blue: 134/255, alpha: 1.0).cgColor
gradientSet = [
[colorOne, colorTwo],
[colorTwo, colorThree],
[colorThree, colorOne]
]
動畫 keyPath 設定 colors 就可以做色彩改變的動畫,toValue 為下一組色彩。
let gradientChangeAnimation = CABasicAnimation(keyPath: "colors")
gradientChangeAnimation.duration = 1.5
gradientChangeAnimation.delegate = self
gradientChangeAnimation.toValue = gradientSet[currentGradient]
gradientChangeAnimation.fillMode = kCAFillModeForwards
gradientChangeAnimation.isRemovedOnCompletion = false
gradientLayer.add(gradientChangeAnimation, forKey: "colorChange")
動畫播完的時候自增長 currentGradient 來改變下一個要使用的色彩組
extension HomeViewController: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
gradientLayer.colors = gradientSet[currentGradient]
currentGradient += 1
}
}
}