[Android] RotateAnimation 回転アニメーション

android.view.animation.Animationクラスを使って、Viewを回転させるRotateAnimationです。
 
1x1.trans - [Android] RotateAnimation 回転アニメーション


Android Studio
2021.2.1

 




RotateAnimation

 
Viewにアニメーションを施したいときはこのAnimationが簡単です。ただし途中で止めるなど込み入ったことはできないので、その場合は Property Animation 等を使いましょう。
 
設定方法は2通りあります。
 

 

XML attributes

 
animationの属性設定は<rotate />タグを使って以下のように設定します。

  • interpolator:補間処理を行う
  • repeatCounter:繰り返し回数
  • fromDegrees:回転の開始角度[°]
  • toDegrees:回転の終了角度[°]
  • pivotX:回転軸のx座標
  • pivotY:回転軸のy座標
  • fillAfter:アニメーション終了時にviewをそのまま残す(true)
  • duration:アニメーションの期間[msec]

 
animフォルダーを作成してxmlファイルをres¥anim¥以下に配置します。
rotation.xml


 

MainActivity.java


 
レイアウトです
activity_main.xml


 
strings.xml


 

 

コードで記述

 
RotateAnimationのConstructorは幾つかあります

  • RotateAnimation(Context context, AttributeSet attrs)
  • RotateAnimation(float fromDegrees, float toDegrees)
  • RotateAnimation(float fromDegrees, float toDegrees, float pivotX, float pivotY)
  • RotateAnimation(float fromDegrees, float toDegrees, int pivotXType, float pivotXValue, int pivotYType, float pivotYValue)

4番目が今回の場合使いやすそうです。

  • RotateAnimation
    • float fromDegrees:回転の開始角度[°]
    • float toDegrees:回転の終了角度[°]
    • int pivotXType:回転軸x座標のタイプ
      • Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF, or Animation.RELATIVE_TO_PARENT
    • float pivotXVal:回転軸のx座標(0->1.0)
    • int pivotYType:回転軸y座標のタイプ
      • Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF, or Animation.RELATIVE_TO_PARENT
    • float pivotYVal:回転軸のy座標(0->1.0)
  • setRepeatCount():繰り返し回数
  • setDuration(msec):アニメーションの期間[msec]
  • startAnimation():アニメーションを開始
  • setAnimationListener():リスナー登録してアニメーション終了のタイミングを取得し、画像を非表示あるいは表示させます。

pivotTypeの3種類は

  • Animation.ABSOLUTE:240 のようなpixel絶対値
  • Animation.RELATIVE_TO_SELF:自分のサイズの割合、0.5fが画像の中心
  • Animation.RELATIVE_TO_PARENT:parentサイズの割合、0.5fが画面中心

MainActivity.java


 
レイアウトです
activity_main.xml


 
strings.xml

 

サンプル動画

 

 
実際は回転しているように見せているだけで、View自体の属性としては動いていません。この例のようにLinearLayoutにもかかわらずボタンと重なって見えるのはそのためでしょうか。
 
 
関連ページ:

 
References:
RotateAnimation
Animation Resources

シェアする

  • このエントリーをはてなブックマークに追加

フォローする