Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Tween 動畫:用 RotateAnimation 實現圖片不停旋轉

編輯:關於 Android 程式設計

本文要介紹的是如何利用 RotateAnimation 讓圖片持續旋轉。Android 平台提供了兩類動畫:一類是 Tween 動畫,透過對場景中的物件不斷做圖形變換(平移、縮放、旋轉)產生動畫;另一類是 Frame 動畫,即順序播放事先做好的圖片,類似電影的原理。本文聚焦於 Tween 動畫中的 rotate 旋轉效果。

在新浪微博客戶端中,每當執行某項操作時,Activity 右上角都會有個不停旋轉的圖標,類似刷新的效果,用以提示使用者「操作中」。這種非模態的提示方式相當值得推薦,下面就來分享如何實現它。

步驟一:定義一個 ImageView

先定義一個 ImageView 來裝載要被旋轉的圖片(其他 View 亦可):

<ImageView
    android:id="@+id/infoOperating"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/operating"
    android:scaleType="center">
</ImageView>

其中 android:src 為圖片內容。接著在 Java 中取得這個 View:

ImageView infoOperatingIV = (ImageView) findViewById(R.id.infoOperating);

步驟二:定義 rotate 旋轉效果

在 res/anim 資料夾下新建 tip.xml 檔:

<set xmlns:android="https://schemas.android.com/apk/res/android">
    <rotate
        android:fromDegrees="0"
        android:toDegrees="359"
        android:duration="500"
        android:repeatCount="-1"
        android:pivotX="50%"
        android:pivotY="50%" />
</set>

其含義是從 0 到 359 度循環旋轉(設為 360 反而會在停止時出現停頓),旋轉中心位於 view 的正中心,每次旋轉耗時 500ms。Java 中載入並設定插值器:

Animation operatingAnim = AnimationUtils.loadAnimation(this, R.anim.tip);
LinearInterpolator lin = new LinearInterpolator();
operatingAnim.setInterpolator(lin);

主要屬性說明

· android:fromDegrees:起始角度。
· android:toDegrees:結束角度,負數為逆時針、正數為順時針。
· android:pivotX / pivotY:旋轉中心的 X/Y 座標,設為 50% 即為物件中心。
· android:duration:旋轉所花的時間(毫秒),可據此計算速度。
· android:interpolator:變化率,可設為加速、減速等,LinearInterpolator 為勻速。
· android:repeatCount:重複次數,-1 表示無限循環。
· android:repeatMode:重複模式,restart(重頭開始)或 reverse(反向重播)。

運行速度 = 運行時間 ÷ 角度差。例如 duration 為 1000、toDegrees 為 360、fromDegrees 為 0,即表示每秒轉一圈。而 android:repeatCount="-1" 搭配 0 到 360 度,就能實現不間斷的循環旋轉。

步驟三:開始與停止旋轉

在操作開始前啟動動畫:

if (operatingAnim != null) {
    infoOperatingIV.startAnimation(operatingAnim);
}

在操作完成時清除動畫:

infoOperatingIV.clearAnimation();

許多朋友不知道如何停止旋轉動畫,於是強行設定轉動圈數來表示操作,卻無法與實際進度匹配。其實只要像上面這樣清除 animation 即可。

最後補充一個實用技巧:當橫屏切換(且 Activity 被設為不重繪)時,可能出現旋轉中心偏移的問題。可以透過重寫 onConfigurationChanged 重新啟動動畫來解決:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (operatingAnim != null && infoOperatingIV != null && operatingAnim.hasStarted()) {
        infoOperatingIV.clearAnimation();
        infoOperatingIV.startAnimation(operatingAnim);
    }
}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved