iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 7
2
Software Development

Android animation 30天上手系列 第 7

Day07 Property animation 進階

Property animation 更進階一些。

ObjectAnimator 一樣可以使用程式碼來實作動畫

例:Rotation

val anim = ObjectAnimator.ofFloat(textView, "rotation", 0.0f, 270.0f)
anim.duration = 1000
anim.start()

ValueAnimator

ObjectAnimator其實是ValueAnimator的子類別,ValueAnimator 不會直接對View做任何操作,我們只是設定動畫的起始結束值,在動畫期間監聽這些的值漸變來操作View

例:監聽一個數值1.0~0.1之間的變動的動畫,並在裡面自行改變View的屬性
Alpha

//建立一個1.0~0.1之間漸變的動畫
val animation = ValueAnimator.ofFloat(1.0f, 0.1f)
//監聽動畫值的改變
animation.addUpdateListener { animation ->
    //在這裡取得從1.0~0.1之間的每個值
    textView.alpha = animation.animatedValue as Float
    textView.requestLayout()
}
//動畫期間
animation.duration = 2000
animation.start()

propertyValuesHolder

從API 23開始,還可以使用PropertyValuesHolder和Keyframe的組合來建立動畫。
Keyframe是來儲存時間與變數的動畫值。Keyframe 的第一個參數為小數值(從0到1),第二個參數為變數值,以確定動畫在整個持續時間內何時到達該值。

Rotate

Keyframe配置如下,在0~1之間配置動畫期間對應的rotate角度。
第0,rotate:0
第0.1,rotate -30
第0.3,rotate 30
第0.6,rotate -30
第0.8,rotate 30
最後1,rotate 0

val frame0 = Keyframe.ofFloat(0f, 0f)
val frame1 = Keyframe.ofFloat(0.1f, -30f)
val frame2 = Keyframe.ofFloat(0.3f, 30f)
val frame3 = Keyframe.ofFloat(0.6f, -30f)
val frame4 = Keyframe.ofFloat(0.8f, 30f)
val frame5 = Keyframe.ofFloat(1f, 0f)
val frameHolder = PropertyValuesHolder.ofKeyframe("rotation", frame0, frame1, frame2, frame3, frame4, frame5)
val animator = ObjectAnimator.ofPropertyValuesHolder(textView, frameHolder)
animator.duration = 500
animator.start()

完整程式:
https://github.com/evanchen76/ValueAnimation

我們介紹完了Android 2個基本的動畫方式:View animation、Porperty animation。
再來要稍微離開一下動畫,我們來講一下繪圖。在做動畫時,除了可以把現有的圖片用來直接加上動畫效果,有時候我們還是得自已來繪圖。下一篇就來介紹使用ShapeDrawable繪圖吧。


上一篇
Day06 Property Animation
下一篇
Day08 ShapeDrawable繪圖
系列文
Android animation 30天上手30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言