[iOS動畫]初學Lottie站在大神的肩膀上,製作出酷炫的App動畫吧!添加骰子動畫
成果展示
修改之前製作的 亂數擲骰子 App 將圖片替換成 動畫 更活潑一點了
製作動機
因為在課程群組內討論到關於動畫,後來自己上網查發現有一套
好用的Library 叫做Lottie 透過它輕鬆的將動畫放入我們的APP
Lottie網站上提供超多大神製作の小動畫可以使用
(但相關規範請依照製作者敘述)
什麼是Lottie
簡單的說透過它可以將AfterEffect 動畫的Json檔讀取出來並讓我們添加在我們的App上,即時呈現動畫模式。
也就是取得JSON格式的動畫,你只要直接拉到Xcode專案,Lottie就可以讀取這個動畫資料
補充資料:
如何使用
與大多數第三方Library相同 pod ‘lottie-ios’ 安裝後打開專案在import Lottie
pod 'lottie-ios'
----------------pod install
----------------在專案內import Lottie
沒使用過第三方可以參考彼得潘這篇
濃縮版
Step1 開Terminal cd到你的專案資料夾
Step2 pod init 產生pod 資料夾
Step3 修改 pod內檔案添加要新增的pod
Step4 pod install 安裝pod
Step5 使用新的xcworkspace執行
Lottie骰子動畫
準備動畫 — 至Lottie官網搜尋Dice關鍵字
程式碼使用Lottie
這兩個個view來裝AnimationView
先新增兩個AnimationView //因為有兩個骰子
這邊修改之前的程式碼將image替換成AnimationView
func ChangeDiceImage(){
EnemyDice=Int.random(in: 0...5)//取亂數0-5YourDice=Int.random(in: 0...5)
animationView.frame=yourDiceView.bounds//設定骰子動畫大小animationView2.frame=EmDiceView.boundsanimationView.animation=Animation.named("\(DiceJSONArray[YourDice])")//設定我方骰子要顯示的動畫是animationView2.animation=Animation.named("\(DiceJSONArray[EnemyDice])")//設定敵方骰子要顯示的動畫是animationView.contentMode = .scaleAspectFill//設定骰子動畫呈現方式animationView2.contentMode = .scaleAspectFillanimationView.loopMode = .playOnce //設定骰子動畫模式這邊設定只跑一次animationView.play()//執行骰子動畫animationView2.play()animationView2.animationSpeed=3//修改骰子動畫的速度animationView.animationSpeed=3 //修改骰子動畫的速度yourDiceView.addSubview(animationView) //將動畫添加到view上顯示EmDiceView.addSubview(animationView2)}
關於動畫初始
viewdidload中我們希望直接顯示最後骰子的結果 也就是最後一幀
因此回到Lottie動畫下載頁面 查看動畫持續時間
可以看到最後是180 而180/60 = 3
所以動畫持續了3秒 所以我們在viewdidload要設定他的畫面為3=最後畫面
animationView.currentTime=3 //設定初始畫面animationView2.currentTime=3//設定初始畫面
附上lottie參考資料
程式碼(branch:newAnitmation)
希望這篇文章能夠幫助到你(妳)
如有錯誤指正
I hope you found this guide helpful. If not, then please let me know either in the comments below, I’m AlberLee
Swift#14