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

Android 以兩張圖實作背景無縫循環平移動畫

編輯:關於 Android 程式設計

要用一張背景圖做出從左到右、周而復始的捲動效果(例如跑馬燈式的滾動雲層、地面),最簡單的技巧是「放兩張一模一樣的圖,各跑一段剛好接得上的位移動畫」。

步驟一:建立兩個 animation XML

第一個從 0%p 移動到 100%p:

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="https://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator"> <translate android:fromXDelta="0%p" android:toXDelta="100%p" android:repeatMode="restart" android:interpolator="@android:anim/linear_interpolator" android:repeatCount="infinite" android:duration="30000" /> </set>

第二個從 -100%p 移動到 0%p:

<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="https://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator"> <translate android:fromXDelta="-100%p" android:toXDelta="0%p" android:repeatMode="restart" android:interpolator="@android:anim/linear_interpolator" android:repeatCount="infinite" android:duration="30000" /> </set>

兩個關鍵:repeatCount="infinite" 讓動畫無限重複,linear_interpolator 確保等速前進——如果用預設的加速插值器,兩張圖的銜接處會出現明顯的速度跳動。

步驟二:在版面中放兩個相同的 ImageView

<ImageView android:id="@+id/animation_top_left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@string/logo" android:src="@drawable/home_animation_bg" /> <ImageView android:id="@+id/animation_top_right" android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@string/logo" android:src="@drawable/home_animation_bg" />

步驟三:分別啟動動畫

Animation anim = AnimationUtils.loadAnimation(mContext, R.anim.home_animation); ImageView animationTopRightView = (ImageView)this.findViewById(R.id.animation_top_right); animationTopRightView.startAnimation(anim);

Animation anim2 = AnimationUtils.loadAnimation(mContext, R.anim.home_animation2); ImageView animationTopLeftView = (ImageView)this.findViewById(R.id.animation_top_left); animationTopLeftView.startAnimation(anim2);

注意事項

兩個動畫的 duration 必須完全相同,背景圖也要具備左右可無縫拼接的特性,否則循環時會出現接縫。若圖片較大或需要更流暢的表現,建議改用 ValueAnimator 搭配 translationX 屬性動畫,並在 Activity 的 onPause() 中暫停動畫以節省電力。

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