3.0以前,android支持兩種動畫模式,tween animation,frame animation,在android3.0中又引入了一個(gè)新的動畫系統(tǒng):property animation,這三種動畫模式在SDK中被稱為property animation,view animation,drawable animation。
1. View Animation(Tween Animation)
View Animation(Tween Animation):補(bǔ)間動畫,給出兩個(gè)關(guān)鍵幀,通過一些算法將給定屬性值在給定的時(shí)間內(nèi)在兩個(gè)關(guān)鍵幀間漸變。
View animation只能應(yīng)用于View對象,而且只支持一部分屬性,如支持縮放旋轉(zhuǎn)而不支持背景顏色的改變。
而且對于View animation,它只是改變了View對象繪制的位置,而沒有改變View對象本身,比如,你有一個(gè)Button,坐標(biāo) (100,100),Width:200,Height:50,而你有一個(gè)動畫使其變?yōu)閃idth:100,Height:100,你會發(fā)現(xiàn)動畫過程中觸 發(fā)按鈕點(diǎn)擊的區(qū)域仍是(100,100)-(300,150)。
View Animation就是一系列View形狀的變換,如大小的縮放,透明度的改變,位置的改變,動畫的定義既可以用代碼定義也可以用XML定義,當(dāng)然,建議用XML定義。
可以給一個(gè)View同時(shí)設(shè)置多個(gè)動畫,比如從透明至不透明的淡入效果,與從小到大的放大效果,這些動畫可以同時(shí)進(jìn)行,也可以在一個(gè)完成之后開始另一個(gè)。
用XML定義的動畫放在/res/anim/文件夾內(nèi),XML文件的根元素可以 為<alpha>,<scale>,<translate>,<rotate>,interpolator 元素或<set>(表示以上幾個(gè)動畫的集合,set可以嵌套)。默認(rèn)情況下,所有動畫是同時(shí)進(jìn)行的,可以通過startOffset屬性設(shè)置 各個(gè)動畫的開始偏移(開始時(shí)間)來達(dá)到動畫順序播放的效果。
可以通過設(shè)置interpolator屬性改變動畫漸變的方式,如AccelerateInterpolator,開始時(shí)慢,然后逐漸加快。默認(rèn)為AccelerateDecelerateInterpolator。
定義好動畫的XML文件后,可以通過類似下面的代碼對指定View應(yīng)用動畫。
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中的定義方式如下:
1 2 3 4 5 6 | < animation-list xmlns: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 >
|
必須以<animation-list>為根元素,以<item>表示要輪換顯示的圖片,duration屬性表示各項(xiàng)顯示的時(shí)間。XML文件要放在/res/drawable/目錄下。示例:
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);
}
我在實(shí)驗(yàn)中遇到兩點(diǎn)問題:
- 要在代碼中調(diào)用Imageview的setBackgroundResource方法,如果直接在XML布局文件中設(shè)置其src屬性當(dāng)觸發(fā)動畫時(shí)會FC。
- 在動畫start()之前要先stop(),不然在第一次動畫之后會停在最后一幀,這樣動畫就只會觸發(fā)一次。
- 最后一點(diǎn)是SDK中提到的,不要在onCreate中調(diào)用start,因?yàn)锳nimationDrawable還沒有完全跟Window相關(guān)聯(lián),如果想要界面顯示時(shí)就開始動畫的話,可以在onWindowFoucsChanged()中調(diào)用start()。
3. Property Animation
屬性動畫,這個(gè)是在Android 3.0中才引進(jìn)的,以前學(xué)WPF時(shí)里面的動畫機(jī)制好像就是這個(gè),它更改的是對象的實(shí)際屬性,在View Animation(Tween Animation)中,其改變的是View的繪制效果,真正的View的屬性保持不變,比如無論你在對話中如何縮放Button的大小,Button的 有效點(diǎn)擊區(qū)域還是沒有應(yīng)用動畫時(shí)的區(qū)域,其位置與大小都不變。而在Property Animation中,改變的是對象的實(shí)際屬性,如Button的縮放,Button的位置與大小屬性值都改變了。而且Property Animation不止可以應(yīng)用于View,還可以應(yīng)用于任何對象。Property Animation只是表示一個(gè)值在一段時(shí)間內(nèi)的改變,當(dāng)值改變時(shí)要做什么事情完全是你自己決定的。
在Property Animation中,可以對動畫應(yīng)用以下屬性:
- Duration:動畫的持續(xù)時(shí)間
- TimeInterpolation:屬性值的計(jì)算方式,如先快后慢
- TypeEvaluator:根據(jù)屬性的開始、結(jié)束值與TimeInterpolation計(jì)算出的因子計(jì)算出當(dāng)前時(shí)間的屬性值
- Repeat Country and behavoir:重復(fù)次數(shù)與方式,如播放3次、5次、無限循環(huán),可以此動畫一直重復(fù),或播放完時(shí)再反向播放
- Animation sets:動畫集合,即可以同時(shí)對一個(gè)對象應(yīng)用幾個(gè)動畫,這些動畫可以同時(shí)播放也可以對不同動畫設(shè)置不同開始偏移
- Frame refreash delay:多少時(shí)間刷新一次,即每隔多少時(shí)間計(jì)算一次屬性值,默認(rèn)為10ms,最終刷新時(shí)間還受系統(tǒng)進(jìn)程調(diào)度與硬件的影響
3.1 Property Animation的工作方式
對于下圖的動畫,這個(gè)對象的X坐標(biāo)在40ms內(nèi)從0移動到40 pixel.按默認(rèn)的10ms刷新一次,這個(gè)對象會移動4次,每次移動40/4=10pixel。

也可以改變屬性值的改變方法,即設(shè)置不同的interpolation,在下圖中運(yùn)動速度先逐漸增大再逐漸減小

下圖顯示了與上述動畫相關(guān)的關(guān)鍵對象

ValueAnimator即表示一個(gè)動畫,包含動畫的開始值,結(jié)束值,持續(xù)時(shí)間等屬性。
ValueAnimator封裝了一個(gè)TimeInterpolator,TimeInterpolator定義了屬性值在開始值與結(jié)束值之間的插值方法。
ValueAnimator還封裝了一個(gè)TypeAnimator,根據(jù)開始、結(jié)束值與TimeIniterpolator計(jì)算得到的值計(jì)算出屬性值。
ValueAnimator根據(jù)動畫已進(jìn)行的時(shí)間跟動畫總時(shí)間(duration)的比計(jì)算出一個(gè)時(shí)間因子(0~1),然后根據(jù)TimeInterpolator計(jì)算出另一個(gè)因子,最后TypeAnimator通過這個(gè)因子計(jì)算出屬性值,如上例中10ms時(shí):
首先計(jì)算出時(shí)間因子,即經(jīng)過的時(shí)間百分比:t=10ms/40ms=0.25
經(jīng)插值計(jì)算(inteplator)后的插值因子:大約為0.15,上述例子中用了AccelerateDecelerateInterpolator,計(jì)算公式為(input即為時(shí)間因子):
(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
最后根據(jù)TypeEvaluator計(jì)算出在10ms時(shí)的屬性值:0.15*(40-0)=6pixel。上例中TypeEvaluator為FloatEvaluator,計(jì)算方法為 :
public Float evaluate(float fraction, Number startValue, Number endValue) {
float startFloat = startValue.floatValue();
return startFloat + fraction * (endValue.floatValue() - startFloat);
}
參數(shù)分別為上一步的插值因子,開始值與結(jié)束值。
3.2 ValueAnimator
ValueAnimator包含Property Animation動畫的所有核心功能,如動畫時(shí)間,開始、結(jié)束屬性值,相應(yīng)時(shí)間屬性值計(jì)算方法等。應(yīng)用Property Animation有兩個(gè)步聚:
- 計(jì)算屬性值
- 根據(jù)屬性值執(zhí)行相應(yīng)的動作,如改變對象的某一屬性。
ValuAnimiator只完成了第一步工作,如果要完成第二步,需要實(shí)現(xiàn)ValueAnimator.onUpdateListener接口,如:
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();
此示例中只是向Logcat輸出了一些信息,可以改為想做的工作。
Animator.AnimatorListener
onAnimationStart()
onAnimationEnd()
onAnimationRepeat()
onAnimationCancel
ValueAnimator.AnimatorUpdateListener
onAnimationUpdate() //通過監(jiān)聽這個(gè)事件在屬性的值更新時(shí)執(zhí)行相應(yīng)的操作,對于ValueAnimator一般要監(jiān)聽此事件執(zhí)行相應(yīng)的動作,不然Animation沒意義(可用于計(jì)時(shí)),在ObjectAnimator(繼承自ValueAnimator)中會自動更新屬性,如無必要不必監(jiān)聽。在函數(shù)中會傳遞一個(gè)ValueAnimator參數(shù),通過此參數(shù)的getAnimatedValue()取得當(dāng)前動畫屬性值。
可以繼承AnimatorListenerAdapter而不是實(shí)現(xiàn)AnimatorListener接口來簡化操作,這個(gè)類對AnimatorListener中的函數(shù)都定義了一個(gè)空函數(shù)體,這樣我們就只用定義想監(jiān)聽的事件而不用實(shí)現(xiàn)每個(gè)函數(shù)卻只定義一空函數(shù)體。
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();
3.3 ObjectAnimator
繼承自ValueAnimator,要指定一個(gè)對象及該對象的一個(gè)屬性,當(dāng)屬性值計(jì)算完成時(shí)自動設(shè)置為該對象的相應(yīng)屬性,即完成了 Property Animation的全部兩步操作。實(shí)際應(yīng)用中一般都會用ObjectAnimator來改變某一對象的某一屬性,但用ObjectAnimator有一 定的限制,要想使用ObjectAnimator,應(yīng)該滿足以下條件:
- 對象應(yīng)該有一個(gè)setter函數(shù):set<PropertyName>(駝峰命名法)
- 如上面的例子中,像ofFloat之類的工場方法,第一個(gè)參數(shù)為對象名,第二個(gè)為屬性名,后面的參數(shù)為可變參數(shù),如果values…參數(shù)只設(shè)置了 一個(gè)值的話,那么會假定為目的值,屬性值的變化范圍為當(dāng)前值到目的值,為了獲得當(dāng)前值,該對象要有相應(yīng)屬性的getter方 法:get<PropertyName>
- 如果有g(shù)etter方法,其應(yīng)返回值類型應(yīng)與相應(yīng)的setter方法的參數(shù)類型一致。
如果上述條件不滿足,則不能用ObjectAnimator,應(yīng)用ValueAnimator代替。
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();
}
});
把一個(gè)TextView的透明度在3秒內(nèi)從0變至1。
根據(jù)應(yīng)用動畫的對象或?qū)傩缘牟煌赡苄枰趏nAnimationUpdate函數(shù)中調(diào)用invalidate()函數(shù)刷新視圖。
3.4 通過AnimationSet應(yīng)用多個(gè)動畫
AnimationSet提供了一個(gè)把多個(gè)動畫組合成一個(gè)組合的機(jī)制,并可設(shè)置組中動畫的時(shí)序關(guān)系,如同時(shí)播放,順序播放等。
以下例子同時(shí)應(yīng)用5個(gè)動畫:
- 播放anim1;
- 同時(shí)播放anim2,anim3,anim4;
- 播放anim5。
1 2 3 4 5 6 | 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
根據(jù)屬性的開始、結(jié)束值與TimeInterpolation計(jì)算出的因子計(jì)算出當(dāng)前時(shí)間的屬性值,android提供了以下幾個(gè)evalutor:
- IntEvaluator:屬性的值類型為int;
- FloatEvaluator:屬性的值類型為float;
- ArgbEvaluator:屬性的值類型為十六進(jìn)制顏色值;
- TypeEvaluator:一個(gè)接口,可以通過實(shí)現(xiàn)該接口自定義Evaluator。
自定義TypeEvalutor很簡單,只需要實(shí)現(xiàn)一個(gè)方法,如FloatEvalutor的定義:
1 2 3 4 5 6 | 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);
}
}
|
根據(jù)動畫執(zhí)行的時(shí)間跟應(yīng)用的Interplator,會計(jì)算出一個(gè)0~1之間的因子,即evalute函數(shù)中的fraction參數(shù),通過上述FloatEvaluator應(yīng)該很好看出其意思。
3.6 TimeInterplator
time interplator定義了屬性值變化的方式,如線性均勻改變,開始慢然后逐漸快等。在Property Animation中是TimeInterplator,在View Animation中是Interplator,這兩個(gè)是一樣的,在3.0之前只有Interplator,3.0之后實(shí)現(xiàn)代碼轉(zhuǎn)移至了 TimeInterplator。Interplator繼承自TimeInterplator,內(nèi)部沒有任何其他代碼。
- AccelerateInterpolator 加速,開始時(shí)慢中間加速
- DecelerateInterpolator 減速,開始時(shí)快然后減速
- AccelerateDecelerateInterolator 先加速后減速,開始結(jié)束時(shí)慢,中間加速
- AnticipateInterpolator 反向 ,先向相反方向改變一段再加速播放
- AnticipateOvershootInterpolator 反向加超越,先向相反方向改變,再加速播放,會超出目的值然后緩慢移動至目的值
- BounceInterpolator 跳躍,快到目的值時(shí)值會跳躍,如目的值100,后面的值可能依次為85,77,70,80,90,100
- CycleIinterpolator 循環(huán),動畫循環(huán)一定次數(shù),值的改變?yōu)橐徽液瘮?shù):Math.sin(2 * mCycles * Math.PI * input)
- LinearInterpolator 線性,線性均勻改變
- OvershottInterpolator 超越,最后超出目的值然后緩慢改變到目的值
- TimeInterpolator 一個(gè)接口,允許你自定義interpolator,以上幾個(gè)都是實(shí)現(xiàn)了這個(gè)接口
3.7 當(dāng)Layout改變時(shí)應(yīng)用動畫
ViewGroup中的子元素可以通過setVisibility使其Visible、Invisible或Gone,當(dāng)有子元素可見性改變時(shí),可以向其應(yīng)用動畫,通過LayoutTransition類應(yīng)用此類動畫:
transition.setAnimator(LayoutTransition.DISAPPEARING, customDisappearingAnim);
通過setAnimator應(yīng)用動畫,第一個(gè)參數(shù)表示應(yīng)用的情境,可以以下4種類型:
- APPEARING 當(dāng)一個(gè)元素變?yōu)閂isible時(shí)對其應(yīng)用的動畫
- CHANGE_APPEARING 當(dāng)一個(gè)元素變?yōu)閂isible時(shí),因系統(tǒng)要重新布局有一些元素需要移動,這些要移動的元素應(yīng)用的動畫
- DISAPPEARING 當(dāng)一個(gè)元素變?yōu)镮nVisible時(shí)對其應(yīng)用的動畫
- CHANGE_DISAPPEARING 當(dāng)一個(gè)元素變?yōu)镚one時(shí),因系統(tǒng)要重新布局有一些元素需要移動,這些要移動的元素應(yīng)用的動畫 disappearing from the container.
第二個(gè)參數(shù)為一Animator。
mTransitioner.setStagger(LayoutTransition.CHANGE_APPEARING, 30);
此函數(shù)設(shè)置動畫持續(xù)時(shí)間,參數(shù)分別為類型與時(shí)間。
3.8 Keyframes
keyFrame是一個(gè) 時(shí)間/值 對,通過它可以定義一個(gè)在特定時(shí)間的特定狀態(tài),而且在兩個(gè)keyFrame之間可以定義不同的Interpolator,就相當(dāng)多個(gè)動畫的拼接,第一個(gè)動 畫的結(jié)束點(diǎn)是第二個(gè)動畫的開始點(diǎn)。KeyFrame是抽象類,要通過ofInt(),ofFloat(),ofObject()獲得適當(dāng)?shù)?KeyFrame,然后通過PropertyValuesHolder.ofKeyframe獲得PropertyValuesHolder對象,如以下 例子:
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);
上述代碼的意思為:設(shè)置btn對象的width屬性值使其:
- 開始時(shí) Width=400
- 動畫開始1/4時(shí) Width=200
- 動畫開始1/2時(shí) Width=400
- 動畫開始3/4時(shí) Width=100
- 動畫結(jié)束時(shí) Width=500
第一個(gè)參數(shù)為時(shí)間百分比,第二個(gè)參數(shù)是在第一個(gè)參數(shù)的時(shí)間時(shí)的屬性值。
定義了一些Keyframe后,通過PropertyValuesHolder類的方法ofKeyframe封裝,然后通過ObjectAnimator.ofPropertyValuesHolder獲得Animator。
用下面的代碼可以實(shí)現(xiàn)同樣的效果:
ObjectAnimator oa=ObjectAnimator.ofInt(btn2, "width", 400,200,400,100,500);
oa.setDuration(2000);
oa.start();
3.9 Animating Views
在View Animation中,對View應(yīng)用Animation并沒有改變View的屬性,動畫的實(shí)現(xiàn)是通過其Parent View實(shí)現(xiàn)的,在View被drawn時(shí)Parents View改變它的繪制參數(shù),draw后再改變參數(shù)invalidate,這樣雖然View的大小或旋轉(zhuǎn)角度等改變了,但View的實(shí)際屬性沒變,所以有效 區(qū)域還是應(yīng)用動畫之前的區(qū)域,比如你把一按鈕放大兩倍,但還是放大這前的區(qū)域可以觸發(fā)點(diǎn)擊事件。為了改變這一點(diǎn),在Android 3.0中給View增加了一些參數(shù)并對這些參數(shù)增加了相應(yīng)的getter/setter函數(shù)(ObjectAnimator要用這些函數(shù)改變這些屬性):
- translationX,translationY:轉(zhuǎn)換坐標(biāo)(control where the View is located as a delta from its left and top coordinates which are set by its layout container.)
- rotation,rotationX,rotationY:旋轉(zhuǎn),rotation用于2D旋轉(zhuǎn)角度,3D中用到后兩個(gè)
- scaleX,scaleY:縮放
- x,y:View的最終坐標(biāo)(utility properties to describe the final location of the View in its container, as a sum of the left and top values and translationX and translationY values.)
- alpha:透明度
跟位置有關(guān)的參數(shù)有3個(gè),以X坐標(biāo)為例,可以通過getLeft(),getX(),getTranslateX()獲得,若有一Button btn2,布局時(shí)其坐標(biāo)為(40,0):
//應(yīng)用動畫之前
btn2.getLeft(); //40
btn2.getX(); //40
btn2.getTranslationX(); //0
//應(yīng)用translationX動畫
ObjectAnimator oa=ObjectAnimator.ofFloat(btn2,"translationX", 200);
oa.setDuration(2000);
oa.start();
/*應(yīng)用translationX動畫后
btn2.getLeft(); //40
btn2.getX(); //240
btn2.getTranslationX(); //200
*/
//應(yīng)用X動畫,假設(shè)沒有應(yīng)用之前的translationX動畫
ObjectAnimator oa=ObjectAnimator.ofFloat(btn2, "x", 200);
oa.setDuration(2000);
oa.start();
/*應(yīng)用X動畫后
btn2.getLeft(); //40
btn2.getX(); //200
btn2.getTranslationX(); //160
*/
無論怎樣應(yīng)用動畫,原來的布局時(shí)的位置通過getLeft()獲得,保持不變;
X是View最終的位置;
translationX為最終位置與布局時(shí)初始位置這差。
所以若就用translationX即為在原來基礎(chǔ)上移動多少,X為最終多少
getX()的值為getLeft()與getTranslationX()的和
對于X動畫,源代碼是這樣的:
case X:
info.mTranslationX = value - mView.mLeft;
break;
Property Animation也可以在XML中定義
- <set> - AnimatorSet
- <animator> - ValueAnimator
- <objectAnimator> - ObjectAnimator
XML文件應(yīng)放大/res/animator/中,通過以下方式應(yīng)用動畫:
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(myContext, R.anim.property_animator);
set.setTarget(myObject);
set.start();
3.10 ViewPropertyAnimator
如果需要對一個(gè)View的多個(gè)屬性進(jìn)行動畫可以用ViewPropertyAnimator類,該類對多屬性動畫進(jìn)行了優(yōu)化,會合并一些invalidate()來減少刷新視圖,該類在3.1中引入。
以下兩段代碼實(shí)現(xiàn)同樣的效果:
PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("x", 50f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y", 100f);
ObjectAnimator.ofPropertyValuesHolder(myView, pvhX, pvyY).start();
myView.animate().x(50f).y(100f);