天天看點

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

3.0以前,android支援兩種動畫模式,tween animation,frame animation,在android3.0中又引入了一個新的動畫系統:property animation,這三種動畫模式在SDK中被稱為property animation,view animation,drawable animation。 可通過NineOldAndroids項目在3.0之前的系統中使用Property Animation

1. View Animation(Tween Animation)

View Animation(Tween Animation):補間動畫,給出兩個關鍵幀,通過一些算法将給定屬性值在給定的時間内在兩個關鍵幀間漸變。

View animation隻能應用于View對象,而且隻支援一部分屬性,如支援縮放旋轉而不支援背景顔色的改變。

而且對于View animation,它隻是改變了View對象繪制的位置,而沒有改變View對象本身,比如,你有一個Button,坐标(100,100),Width:200,Height:50,而你有一個動畫使其變為Width:100,Height:100,你會發現動畫過程中觸發按鈕點選的區域仍是(100,100)-(300,150)。

View Animation就是一系列View形狀的變換,如大小的縮放,透明度的改變,位置的改變,動畫的定義既可以用代碼定義也可以用XML定義,當然,建議用XML定義。

可以給一個View同時設定多個動畫,比如從透明至不透明的淡入效果,與從小到大的放大效果,這些動畫可以同時進行,也可以在一個完成之後開始另一個。

用XML定義的動畫放在/res/anim/檔案夾内,XML檔案的根元素可以為<alpha>,<scale>,<translate>,<rotate>,interpolator元素或<set>(表示以上幾個動畫的集合,set可以嵌套)。預設情況下,所有動畫是同時進行的,可以通過startOffset屬性設定各個動畫的開始偏移(開始時間)來達到動畫順序播放的效果。

可以通過設定interpolator屬性改變動畫漸變的方式,如AccelerateInterpolator,開始時慢,然後逐漸加快。預設為AccelerateDecelerateInterpolator。

定義好動畫的XML檔案後,可以通過類似下面的代碼對指定View應用動畫。

ImageView spaceshipImage = (ImageView)findViewById(R.id.spaceshipImage);
Animation hyperspaceJumpAnimation=AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump);
spaceshipImage.startAnimation(hyperspaceJumpAnimation);      

2. Drawable Animation(Frame Animation)

Drawable Animation(Frame Animation):幀動畫,就像GIF圖檔,通過一系列Drawable依次顯示來模拟動畫的效果。在XML中的定義方式如下:

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true">
    <item android:drawable="@drawable/rocket_thrust1" android:duration="200" />
    <item android:drawable="@drawable/rocket_thrust2" android:duration="200" />
    <item android:drawable="@drawable/rocket_thrust3" android:duration="200" />
</animation-list>      
Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

必須以<animation-list>為根元素,以<item>表示要輪換顯示的圖檔,duration屬性表示各項顯示的時間。XML檔案要放在/res/drawable/目錄下。示例:

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation
protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imageView = (ImageView) findViewById(R.id.imageView1);
        imageView.setBackgroundResource(R.drawable.drawable_anim);
        anim = (AnimationDrawable) imageView.getBackground();
    }

    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            anim.stop();
            anim.start();
            return true;
        }
        return super.onTouchEvent(event);
    }      
Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

我在實驗中遇到兩點問題:

  1. 要在代碼中調用Imageview的setBackgroundResource方法,如果直接在XML布局檔案中設定其src屬性當觸發動畫時會FC。
  2. 在動畫start()之前要先stop(),不然在第一次動畫之後會停在最後一幀,這樣動畫就隻會觸發一次。
  3. 最後一點是SDK中提到的,不要在onCreate中調用start,因為AnimationDrawable還沒有完全跟Window相關聯,如果想要界面顯示時就開始動畫的話,可以在onWindowFoucsChanged()中調用start()。

3. Property Animation

屬性動畫,這個是在Android 3.0中才引進的,以前學WPF時裡面的動畫機制好像就是這個,它更改的是對象的實際屬性,在View Animation(Tween Animation)中,其改變的是View的繪制效果,真正的View的屬性保持不變,比如無論你在對話中如何縮放Button的大小,Button的有效點選區域還是沒有應用動畫時的區域,其位置與大小都不變。而在Property Animation中,改變的是對象的實際屬性,如Button的縮放,Button的位置與大小屬性值都改變了。而且Property Animation不止可以應用于View,還可以應用于任何對象。Property Animation隻是表示一個值在一段時間内的改變,當值改變時要做什麼事情完全是你自己決定的。

在Property Animation中,可以對動畫應用以下屬性:

  • Duration:動畫的持續時間
  • TimeInterpolation:屬性值的計算方式,如先快後慢
  • TypeEvaluator:根據屬性的開始、結束值與TimeInterpolation計算出的因子計算出目前時間的屬性值
  • Repeat Count and behavoir:重複次數與方式,如播放3次、5次、無限循環,可以此動畫一直重複,或播放完時再反向播放
  • Animation sets:動畫集合,即可以同時對一個對象應用幾個動畫,這些動畫可以同時播放也可以對不同動畫設定不同開始偏移
  • Frame refreash delay:多少時間重新整理一次,即每隔多少時間計算一次屬性值,預設為10ms,最終重新整理時間還受系統程序排程與硬體的影響

3.1 Property Animation的工作方式

對于下圖的動畫,這個對象的X坐标在40ms内從0移動到40 pixel.按預設的10ms重新整理一次,這個對象會移動4次,每次移動40/4=10pixel。

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

也可以改變屬性值的改變方法,即設定不同的interpolation,在下圖中運動速度先逐漸增大再逐漸減小

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

下圖顯示了與上述動畫相關的關鍵對象

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

ValueAnimator  表示一個動畫,包含動畫的開始值,結束值,持續時間等屬性。

ValueAnimator封裝了一個TimeInterpolator,TimeInterpolator定義了屬性值在開始值與結束值之間的插值方法。

ValueAnimator還封裝了一個TypeAnimator,根據開始、結束值與TimeIniterpolator計算得到的值計算出屬性值。

ValueAnimator根據動畫已進行的時間跟動畫總時間(duration)的比計算出一個時間因子(0~1),然後根據TimeInterpolator計算出另一個因子,最後TypeAnimator通過這個因子計算出屬性值,如上例中10ms時:

首先計算出時間因子,即經過的時間百分比:t=10ms/40ms=0.25

經插值計算(inteplator)後的插值因子:大約為0.15,上述例子中用了AccelerateDecelerateInterpolator,計算公式為(input即為時間因子):

(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;        

最後根據TypeEvaluator計算出在10ms時的屬性值:0.15*(40-0)=6pixel。上例中TypeEvaluator為FloatEvaluator,計算方法為 :

public Float evaluate(float fraction, Number startValue, Number endValue) {
    float startFloat = startValue.floatValue();
    return startFloat + fraction * (endValue.floatValue() - startFloat);
}      

參數分别為上一步的插值因子,開始值與結束值。

3.2 ValueAnimator

ValueAnimator包含Property Animation動畫的所有核心功能,如動畫時間,開始、結束屬性值,相應時間屬性值計算方法等。應用Property Animation有兩個步聚:

  1. 計算屬性值
  2. 根據屬性值執行相應的動作,如改變對象的某一屬性。

ValuAnimiator隻完成了第一步工作,如果要完成第二步,需要實作ValueAnimator.onUpdateListener接口,這個接口隻有一個函數onAnimationUpdate(),在這個函數中會傳入ValueAnimator對象做為參數,通過這個ValueAnimator對象的getAnimatedValue()函數可以得到目前的屬性值如:

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation
ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f);
animation.setDuration(1000);
animation.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        Log.i("update", ((Float) animation.getAnimatedValue()).toString());
    }
});
animation.setInterpolator(new CycleInterpolator(3));
animation.start();      
Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

此示例中隻是向Logcat輸出了一些資訊,可以改為想做的工作。

Animator.AnimatorListener

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation
onAnimationStart()

onAnimationEnd()

onAnimationRepeat()

//當動畫被取消時調用,同時會調用onAnimationEnd().
onAnimationCancel()      
Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

ValueAnimator.AnimatorUpdateListener

onAnimationUpdate()  //通過監聽這個事件在屬性的值更新時執行相應的操作,對于ValueAnimator一般要監聽此事件執行相應的動作,不然Animation沒意義,在ObjectAnimator(繼承自ValueAnimator)中會自動更新屬性,如無必要不必監聽。在函數中會傳遞一個ValueAnimator參數,通過此參數的getAnimatedValue()取得目前動畫屬性值。      

可以繼承AnimatorListenerAdapter而不是實作AnimatorListener接口來簡化操作,這個類對AnimatorListener中的函數都定義了一個空函數體,這樣我們就隻用定義想監聽的事件而不用實作每個函數卻隻定義一空函數體。

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation
ObjectAnimator oa=ObjectAnimator.ofFloat(tv, "alpha", 0f, 1f);
oa.setDuration(3000);
oa.addListener(new AnimatorListenerAdapter(){
    public void on AnimationEnd(Animator animation){
        Log.i("Animation","end");
    }
});
oa.start();      
Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

3.3 ObjectAnimator

繼承自ValueAnimator,要指定一個對象及該對象的一個屬性,當屬性值計算完成時自動設定為該對象的相應屬性,即完成了Property Animation的全部兩步操作。實際應用中一般都會用ObjectAnimator來改變某一對象的某一屬性,但用ObjectAnimator有一定的限制,要想使用ObjectAnimator,應該滿足以下條件:

  • 對象應該有一個setter函數:set<PropertyName>(駝峰命名法)
  • 如上面的例子中,像ofFloat之類的工場方法,第一個參數為對象名,第二個為屬性名,後面的參數為可變參數,如果values…參數隻設定了一個值的話,那麼會假定為目的值,屬性值的變化範圍為目前值到目的值,為了獲得目前值,該對象要有相應屬性的getter方法:get<PropertyName>
  • 如果有getter方法,其應傳回值類型應與相應的setter方法的參數類型一緻。

如果上述條件不滿足,則不能用ObjectAnimator,應用ValueAnimator代替。

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation
tv=(TextView)findViewById(R.id.textview1);
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    ObjectAnimator oa=ObjectAnimator.ofFloat(tv, "alpha", 0f, 1f);
    oa.setDuration(3000);
    oa.start();
  }
});      
Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

把一個TextView的透明度在3秒内從0變至1。

根據應用動畫的對象或屬性的不同,可能需要在onAnimationUpdate函數中調用invalidate()函數重新整理視圖。

3.4 通過AnimationSet應用多個動畫

AnimationSet提供了一個把多個動畫組合成一個組合的機制,并可設定組中動畫的時序關系,如同時播放,順序播放等。

以下例子同時應用5個動畫:

  1. 播放anim1;
  2. 同時播放anim2,anim3,anim4;
  3. 播放anim5。
AnimatorSet bouncer = new AnimatorSet();
bouncer.play(anim1).before(anim2);
bouncer.play(anim2).with(anim3);
bouncer.play(anim2).with(anim4)
bouncer.play(anim5).after(amin2);
animatorSet.start();      

3.5 TypeEvalutors

根據屬性的開始、結束值與TimeInterpolation計算出的因子計算出目前時間的屬性值,android提供了以下幾個evalutor:

  • IntEvaluator:屬性的值類型為int;
  • FloatEvaluator:屬性的值類型為float;
  • ArgbEvaluator:屬性的值類型為十六進制顔色值;
  • TypeEvaluator:一個接口,可以通過實作該接口自定義Evaluator。

自定義TypeEvalutor很簡單,隻需要實作一個方法,如FloatEvalutor的定義:

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation
public class FloatEvaluator implements TypeEvaluator {
    public Object evaluate(float fraction, Object startValue, Object endValue) {
        float startFloat = ((Number) startValue).floatValue();
        return startFloat + fraction * (((Number) endValue).floatValue() - startFloat);
    }
}      
Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

根據動畫執行的時間跟應用的Interplator,會計算出一個0~1之間的因子,即evalute函數中的fraction參數,通過上述FloatEvaluator應該很好看出其意思。

3.6 TimeInterplator

Time interplator定義了屬性值變化的方式,如線性均勻改變,開始慢然後逐漸快等。在Property Animation中是TimeInterplator,在View Animation中是Interplator,這兩個是一樣的,在3.0之前隻有Interplator,3.0之後實作代碼轉移至了TimeInterplator。Interplator繼承自TimeInterplator,内部沒有任何其他代碼。

  • AccelerateInterpolator          加速,開始時慢中間加速
  • DecelerateInterpolator         減速,開始時快然後減速
  • AccelerateDecelerateInterolator    先加速後減速,開始結束時慢,中間加速
  • AnticipateInterpolator        反向 ,先向相反方向改變一段再加速播放
  • AnticipateOvershootInterpolator    反向加回彈,先向相反方向改變,再加速播放,會超出目的值然後緩慢移動至目的值
  • BounceInterpolator         跳躍,快到目的值時值會跳躍,如目的值100,後面的值可能依次為85,77,70,80,90,100
  • CycleIinterpolator         循環,動畫循環一定次數,值的改變為一正弦函數:Math.sin(2 * mCycles * Math.PI * input)
  • LinearInterpolator         線性,線性均勻改變
  • OvershottInterpolator        回彈,最後超出目的值然後緩慢改變到目的值
  • TimeInterpolator           一個接口,允許你自定義interpolator,以上幾個都是實作了這個接口

3.7 當Layout改變時應用動畫

ViewGroup中的子元素可以通過setVisibility使其Visible、Invisible或Gone,當有子元素可見性改變時(VISIBLE、GONE),可以向其應用動畫,通過LayoutTransition類應用此類動畫:

transition.setAnimator(LayoutTransition.DISAPPEARING, customDisappearingAnim);      

通過setAnimator應用動畫,第一個參數表示應用的情境,可以以下4種類型:

  • APPEARING        當一個元素在其父元素中變為Visible時對這個元素應用動畫
  • CHANGE_APPEARING    當一個元素在其父元素中變為Visible時,因系統要重新布局有一些元素需要移動,對這些要移動的元素應用動畫
  • DISAPPEARING       當一個元素在其父元素中變為GONE時對其應用動畫
  • CHANGE_DISAPPEARING   當一個元素在其父元素中變為GONE時,因系統要重新布局有一些元素需要移動,這些要移動的元素應用動畫.

第二個參數為一Animator。

mTransitioner.setStagger(LayoutTransition.CHANGE_APPEARING, 30);      

此函數設定動畫延遲時間,參數分别為類型與時間。

3.8 Keyframes

keyFrame是一個 時間/值 對,通過它可以定義一個在特定時間的特定狀态,即關鍵幀,而且在兩個keyFrame之間可以定義不同的Interpolator,就好像多個動畫的拼接,第一個動畫的結束點是第二個動畫的開始點。KeyFrame是抽象類,要通過ofInt(),ofFloat(),ofObject()獲得适當的KeyFrame,然後通過PropertyValuesHolder.ofKeyframe獲得PropertyValuesHolder對象,如以下例子:

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation
Keyframe kf0 = Keyframe.ofInt(0, 400);
Keyframe kf1 = Keyframe.ofInt(0.25f, 200);
Keyframe kf2 = Keyframe.ofInt(0.5f, 400);
Keyframe kf4 = Keyframe.ofInt(0.75f, 100);
Keyframe kf3 = Keyframe.ofInt(1f, 500);
PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe("width", kf0, kf1, kf2, kf4, kf3);
ObjectAnimator rotationAnim = ObjectAnimator.ofPropertyValuesHolder(btn2, pvhRotation);
rotationAnim.setDuration(2000);      
Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

上述代碼的意思為:設定btn對象的width屬性值使其:

  • 開始時 Width=400
  • 動畫開始1/4時 Width=200
  • 動畫開始1/2時 Width=400
  • 動畫開始3/4時 Width=100
  • 動畫結束時 Width=500

第一個參數為時間百分比,第二個參數是在第一個參數的時間時的屬性值。 定義了一些Keyframe後,通過PropertyValuesHolder類的方法ofKeyframe一個PropertyValuesHolder對象,然後通過ObjectAnimator.ofPropertyValuesHolder獲得一個Animator對象。 用下面的代碼可以實作同樣的效果(上述代碼時間值是線性,變化均勻):

ObjectAnimator oa=ObjectAnimator.ofInt(btn2, "width", 400,200,400,100,500);
oa.setDuration(2000);
oa.start();      

3.9 Animating Views

在View Animation中,對View應用Animation并沒有改變View的屬性,動畫的實作是通過其Parent View實作的,在View被drawn時Parents View改變它的繪制參數,draw後再改變參數invalidate,這樣雖然View的大小或旋轉角度等改變了,但View的實際屬性沒變,是以有效區域還是應用動畫之前的區域,比如你把一按鈕放大兩倍,但還是放大這前的區域可以觸發點選事件。為了改變這一點,在Android 3.0中給View增加了一些參數并對這些參數增加了相應的getter/setter函數(ObjectAnimator要用這些函數改變這些屬性):

  • translationX,translationY: View相對于原始位置的偏移量
  • rotation,rotationX,rotationY: 旋轉,rotation用于2D旋轉角度,3D中用到後兩個
  • scaleX,scaleY: 縮放比
  • x,y: View的最終坐标,是View的left,top位置加上translationX,translationY
  • alpha: 透明度

跟位置有關的參數有3個,以X坐标為例,可以通過getLeft(),getX(),getTranslateX()獲得,若有一Button btn2,布局時其坐标為(40,0):

Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation
//應用動畫之前
btn2.getLeft();    //40
btn2.getX();    //40
btn2.getTranslationX();    //0
//應用translationX動畫
ObjectAnimator oa=ObjectAnimator.ofFloat(btn2,"translationX", 200);
oa.setDuration(2000);
oa.start();
/*應用translationX動畫後
btn2.getLeft();    //40
btn2.getX();    //240
btn2.getTranslationX();    //200
*/
//應用X動畫,假設沒有應用之前的translationX動畫
ObjectAnimator oa=ObjectAnimator.ofFloat(btn2, "x", 200);
oa.setDuration(2000);
oa.start();
/*應用X動畫後
btn2.getLeft();    //40
btn2.getX();    //200
btn2.getTranslationX();    //160
*/      
Android動畫學習筆記-Android Animation 1. View Animation(Tween Animation) 2. Drawable Animation(Frame Animation) 3. Property Animation

無論怎樣應用動畫,原來的布局時的位置通過getLeft()獲得,保持不變;   X是View最終的位置;   translationX為最終位置與布局時初始位置這差。   是以若就用translationX即為在原來基礎上移動多少,X為最終多少   getX()的值為getLeft()與getTranslationX()的和   對于X動畫,源代碼是這樣的:

case X:
       info.mTranslationX = value - mView.mLeft;
       break;      

Property Animation也可以在XML中定義

  • <set> - AnimatorSet
  • <animator> - ValueAnimator
  • <objectAnimator> - ObjectAnimator

XML檔案應放大/res/animator/中,通過以下方式應用動畫:

AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(myContext, R.anim.property_animator);
set.setTarget(myObject);
set.start();      

3.10 ViewPropertyAnimator

如果需要對一個View的多個屬性進行動畫可以用ViewPropertyAnimator類,該類對多屬性動畫進行了優化,會合并一些invalidate()來減少重新整理視圖,該類在3.1中引入。

以下兩段代碼實作同樣的效果: 

PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("x", 50f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y", 100f);
ObjectAnimator.ofPropertyValuesHolder(myView, pvhX, pvyY).start();      
myView.animate().x(50f).y(100f);      

作者: AngelDevil

出處: www.cnblogs.com/angeldevil

歡迎通路我的個人站點:angeldevil.me

轉載請注明出處!

繼續閱讀