iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 23
0

https://ithelp.ithome.com.tw/upload/images/20180111/20107329tAJKbqk5ww.png
通過 CAGradientLayer 可以很容易實現漸變色效果,而且這個漸變色的效果可以拿來做動畫。


Gradient Animation

Gradient Animation

一開始的背景圖就是用了漸變效果,而當點下按鈕以後,配合 CABasicAnimation 做漸變色切換的動畫。


CAGradientLayer

https://ithelp.ithome.com.tw/upload/images/20180111/20107329TlEJ4B2Bxe.png
給 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)

CABasicAnimation

先建立色彩組,用來切換色彩。

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
        }
    }
}

Reference


上一篇
Transitions - UIView Transition (視圖轉場動畫)
下一篇
StartPageMovie - 啟動頁影片
系列文
iOS Swift x Layout x Animation x Transition30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言