星期四, 1月 26, 2012

Animation (八)

Android應用程式學習筆記

Animating Views

屬性動畫系統允許有效率的視圖物件的動畫,並提供一些超越視圖動畫系統的好處。視圖動畫系統藉由改變它們繪製地方法來變換視圖物件,在每個View容器中處理,因為View自己沒有屬性可以處理,結果View已經動畫了,但是View物件自己卻沒有改變。這造成物件的行為還留在原本的位置,雖然它已經繪製到不同位置了。

屬性動畫系統可以藉由改變視圖物件的真實屬性完成試圖物件在屏幕上的動畫,此外,視圖會在數值改變時自動呼叫invalidate()方法刷新屏幕,在View類別有新的屬性方便屬性動畫:
  • translationX與translationY:這些屬性控制視圖位置,它的左與頂部座標由它的布局容器設定。
  • rotation、rotationX與rotationY:這些屬性控制View在2D與3D下繞著支點的旋轉。
  • scaleX與scaleY:這些屬性控制View在2D下對於支點的伸縮。
  • pivotX與pivotY:這些屬性控制之點的位置,預設的支點值為View物件的中心位置。
  • x 與 y:這些屬性用來描述View物件在容器中位置。
  • alpha:顯示View物件的透明度,預設數值為1表示不透明,數值為0表示透明。
動畫一個View物件的屬性,比如顏色或是旋轉數值,所有你需要做的就是建立一個屬性animator,並指定你想動畫視圖動畫屬性。例如:

ObjectAnimator.ofFloat(myView, "rotation", 0f, 360f);


Animating with ViewPropertyAnimator

使用一個單一的底層animator,ViewProperyAnimator提供了一個同時動畫一個View物件的許多屬性的簡單方式。它的行為很像一個ObjectAnimator,因為它確實改變了View物件的屬性,但當要同時動畫多個屬性時,ViewPropertyAnimator又更有效率。此外,使用ViewPropertyAnimator的程式碼更加簡潔與容易閱讀。以下程式碼片段顯示使用多個ObjectAnimator、單一ObjectAnimator與ViewPropertyAnimator同時動畫View的x與y屬性的不同。

Multiple ObjectAnimator objects
ObjectAnimator animX = ObjectAnimator.ofFloat(myView, "x", 50f);
ObjectAnimator animY = ObjectAnimator.ofFloat(myView, "y", 100f);
AnimatorSet animSetXY = new AnimatorSet();
animSetXY.playTogether(animX, animY);
animSetXY.start();
One ObjectAnimator
PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("x", 50f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y", 100f);
ObjectAnimator.ofPropertyValuesHolder(myView, pvhX, pvyY).start();
ViewPropertyAnimator
myView.animate().x(50f).y(100f);


Declaring Animation in XML

屬性動畫系統讓你用xml宣告屬性動畫,取代編成的方式。藉著在xml中定義動畫,你可以更輕易地重複在多個activities中重複使用,更輕鬆地編輯動畫序列。

為了區別使用新的屬性動畫APIs的動畫檔案與使用視圖動畫框架的,你應該將屬性動畫xml檔案存在res/animator目錄,使用animator目錄是自選的,如果你想要使用在eclipse ADT 的布局工具,你必須設定為animator,因為ADT只會在res/animator目錄搜尋屬性動畫。

以下是屬性動畫類別中支援xml的標籤:
  • ValueAnimator - <animator>
  • ObjectAnimator - <objectAnimator>
  • AnimatorSet - <set>


<set android:ordering="sequentially">
    <set>
        <objectAnimator
            android:propertyName="x"
            android:duration="500"
            android:valueTo="400"
            android:valueType="intType"/>
        <objectAnimator
            android:propertyName="y"
            android:duration="500"
            android:valueTo="300"
            android:valueType="intType"/>
    </set>
    <objectAnimator
        android:propertyName="alpha"
        android:duration="500"
        android:valueTo="1f"/>
</set>
為了運行此動畫,必須在妳的程式碼中將XML資源擴展到妳的Animator物件,並且在啟動前設定動畫的目標物件,呼叫serTarget()方法設定單一物件。

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

沒有留言:

張貼留言