2
4

More than 1 year has passed since last update.

【Android】ObjectAnimatorで遊ぼう

Posted at

※当記事は表示している画像にラグがあります。お許しください。

ObjectAnimatorを使うとこんなことができました。

Transition.gif

某シューティングゲー??

今回はObjectAnimatorの基本的なアニメーションをまとめます。

ObjectAnimator

Viewをアニメートしてくれます。
アニメーション対象のViewをTargetと呼び、具体的にどうアニメーションするかを定義しているのがプロパティです。

代表的なプロパティは以下
- ROTATION:回転
- TRANSLATION:移動
- SCALE:拡大縮小
- ALPHA:透過

ほか、いわゆるセッターゲッターがある各属性(backGroudColorのような)なら、大体これでアニメーション化できるとのこと。

kotlin.kt
ObjectAnimator.ofFloat(
targetView,
Property,  
float... values           
).start()

ROTATION:回転

クリックリスナに以下処理を書きましょう。(→このViewはこちらの記事で

kotlin.kt
val animator = ObjectAnimator.ofFloat(targetView, View.ROTATION, 0f, 360f) // 0°Start 360°End
animator.duration = 2000 // アニメーション期間 Defaultは300ms
animator.start()

※ラグってますが、手元のエミュレータではきれいに回ってます

Rotation.gif

TRANSLATION:移動

val animator = ObjectAnimator.ofFloat(targetView, View.TRANSLATION_Y, 800f) // Y軸方向(マイナス)に800動かすanimator.repeatCount = 1 // アニメーションをリピート
animator.repeatMode = ObjectAnimator.REVERSE // リピート設定
animator.start()

開始位置は上にずらしてます。
Transition.gif

Scale : 拡大縮小

kotlin.kt
val scaleX = PropertyValuesHolder.ofFloat(View.SCALE_X, 4f)
val scaleY = PropertyValuesHolder.ofFloat(View.SCALE_Y, 4f)
val animator = ObjectAnimator.ofPropertyValuesHolder(targetView, scaleX, scaleY)
animator.repeatCount = 1 
animator.repeatMode = ObjectAnimator.REVERSE 
animator.start()

ScaleアニメーションはXとY双方に関してアニメーションプロパティを設定する必要があります。
複数のプロパティを設定する一つの方法として、PropertyValuesHolderがあります。
PropertyValuesHodler(X, value)
PropertyValuesHodler (Y, value)
ObjectAnimater.ofPropertyValuesHolder(view, holderx, holdery)
といった形で、ある種、いくつかのプロパティを合成するイメージですね。

Scale.gif

Alpha : 透過

val animator = ObjectAnimator.ofFloat(targetView, View.ALPHA, 0f) // 0.0へ透過
animator.duration = 1000
animator.start()

Alpha.gif

他プロパティ

上でちょっと書いた、セッターゲッターがあるプロパティであれば、アニメーション化できます。

val animator = ObjectAnimator.ofArgb(targetView.parent,
"backgroundColor", Color.BLACK, Color.WHITE)
animator.setDuration(500)
animator.repeatCount = 1
animator.repeatMode = ObjectAnimator.REVERSE
animator.start()

Alpha.gif

応用

この辺組み合わせると、冒頭の以下のようなアニメーションが作れます。次記事でざっくり解説予定。
Transition.gif

終わり

ラグすみません。改善予定。。

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4