Android 平台提供了兩種動畫一種是 Frame動畫,即順序的播放事先做好的圖像,與gif圖片或者說跟放電影的原理相似,另一種是Tween動畫,就是對場景里的對象不斷的進行圖像變化來產生動畫效果(旋轉、平移、放縮和漸變),本文中是是介紹第一種幀動畫的的實現,幀動畫是一種常見的動畫形式(Frame By Frame),其原理是在“連續的關鍵幀”中分解動畫動作,也就是在時間軸的每幀上逐幀繪制不同的內容,使其連續播放而成動畫。 因為逐幀動畫的幀序列內容不一樣,不但給制作增加了負擔而且最終輸出的文件量也很大,但它的優勢也很明顯:逐幀動畫具有非常大的靈活性,幾乎可以表現任何想表現的內容,而它類似與電影的播放模式,很適合於表演細膩的動畫。
布局文件
首先在res中新建一個drawable文件夾,將需要展示的圖片放在里面,同樣的還有展示圖片的fight.xml文件,代碼如下:
<?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false" > <item android:drawable="@drawable/fight_1" android:duration="200"/> <item android:drawable="@drawable/fight_2" android:duration="200"/> <item android:drawable="@drawable/fight_3" android:duration="200"/> <item android:drawable="@drawable/fight_4" android:duration="200"/> <item android:drawable="@drawable/fight_5" android:duration="200"/> <item android:drawable="@drawable/fight_6" android:duration="200"/> <item android:drawable="@drawable/fight_7" android:duration="200"/> <item android:drawable="@drawable/fight_8" android:duration="200"/> <item android:drawable="@drawable/fight_9" android:duration="200"/> <item android:drawable="@drawable/fight_10" android:duration="200"/> <item android:drawable="@drawable/fight_11" android:duration="200"/> </animation-list>
文件夾的布局:
Demo實現
MainActivity定義一個ImageView,oncreate中調用:
ImageView fightImage = (ImageView) findViewById(R.id.image_aniation); fightImage.setBackgroundResource(R.drawable.fight); fightnimation = (AnimationDrawable) fightImage.getBackground();
不能加載的時候立即調用,需要在觸摸的時候調用:
public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { fightnimation.start(); return true; } return super.onTouchEvent(event); }
效果如下: