Android動畫原理總結
電腦實現動畫的原理 :1 跟放電影一樣,定時改變映像。 2 必須有定時器動畫的分類 : 屬性動畫;視圖動畫;drawable 動畫drawable 動畫 --靜態圖片動畫----需要準備好一幀幀的圖片,打包體積大。只有屬性動畫和 視圖動畫不能完成時,才考慮它。屬性動畫和視圖動畫都是動態產生每幀的映像的,不影響程式的體積。屬性動畫是來替代視圖動畫的,目標不限於 view 類對象,目標對象即使不可見也可以動。屬性動畫的實質就是 定時器發生---->計算新的屬性的值 ---->將新值設定到目標對象的屬性中---->目標對象重新整理----> UI 發生變化。不斷的重複這個過程,就出現動畫了。推薦使用屬性動畫。相關的類 :1 Animator 基類,不能直接使用。 2 ValueAnimator ,實現了動畫架構的大部分功能,但是只計算屬性的值,並不把這個值設定到對象中。如果用的話,需要我們自己寫一個偵聽類,偵聽 ValueAnimator 的事件,然後將屬性的值設定到對象中,可以用它,但有更好的, 當更好用的不能用時,才考慮這個。 3 ObjectAnimator ValueAnimator 的子類,它就是更好的選擇。它會計算對象 的屬性值,然後將新值設定到對象的那個屬性。大部分時間使用這個類即可。 4 AnimatorSet Set 表示動畫集合。它包含多個動畫。這多個動畫可以同時執行, 可以一個個順序執行,也可以執行完一個然後隔一段時間再執行另一個。使用屬性動畫類 :要讓一個對象動起來,需要向 ObjectAnimator 指定這個對象, 指定要改變的那個屬性,指定一個期間,還要指定動畫本身的參數,比如平移的話,要指定開始位置和結束位置。勻速平移
ObjectAnimator anim = ObjectAnimator.ofFloat( btnTarget,"translationX",0f,200f);anim.setDuration(2000); anim.start();
旋轉
ObjectAnimator anim = ObjectAnimator .ofFloat( btnTarget, "rotationX", 0f, 180f); anim.setDuration(2000); anim.start();
使用動畫集合類 :
AnimatorSet set = new AnimatorSet(); ObjectAnimator anim1 = ObjectAnimator.ofFloat(btnTarget,"rotationX",0f,180f); anim1.setDuration(2000); ObjectAnimator anim2 = ObjectAnimator.ofFloat(btnTarget,"rotationX",180f,0f); anim2.setDuration(2000); ObjectAnimator anim3 = ObjectAnimator.ofFloat(btnTarget,"rotationY",0f,180f); anim3.setDuration(2000); ObjectAnimator anim4 = ObjectAnimator.ofFloat(btnTarget,"rotationY",180f,0f); anim4.setDuration(2000);set.play(anim1).before(anim2);set.play(anim3).before(anim4);set.start();
xml 實現 1 單個動畫
<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--> <cke:objectanimator xmlns:android="http://schemas.android.com/apk/res/an droid" android:propertyname="translationX" android:duration="2000" android:valuefrom="0dp" android:valueto="200dp" android:valuetype="floatType"></cke:objectanimator>
代碼:
ObjectAnimator anim =(ObjectAnimator)AnimatorInflater.loadAnimator( MainActivity.this,R.animator.rotate_anim); anim.setTarget(btnTarget); anim.start();
多個動畫
<set xmlns:android="http://schemas.android.com/apk/res/android" android:ordering="sequentially"> <cke:objectanimator android:propertyname="rotationX" android:duration="2000" android:valuefrom="0" android:valueto="180" android:valuetype="floatType"> <cke:objectanimator android:propertyname="rotationX" android:duration="2000" android:valuefrom="180" android:valueto="0" android:valuetype="floatType"> </cke:objectanimator></cke:objectanimator></set>
代碼:
AnimatorSet set = (AnimatorSet)AnimatorInflater.loadAnimator( MainActivity.this,R.animator.rotate_anim); set.setTarget(btnTarget); set.start();
總結: 動畫離不了定時器; android 系統有三種動畫 ; 屬性動畫可以在純程式中使用,也可以在 xml 中使用,xml 必須放在 res/animator 檔案夾下;為了更好的重用,應盡量在 xml 中定義動畫;屬性動畫的實質就是定時改變對象的屬性的值;可以使用動畫集合類,產生出複雜的動畫