android中的自定義動畫有兩種模式:tweened animation和frame by frame。這裏介紹一種通過xml實現tweened animation的方法。
tweened animation(漸變動畫),有四種動畫類型:alpha(透明度)、scale(尺寸伸縮)、translate(位置變換)和rotate(圖形旋轉)。
首先,建立一個叫Animation的項目,在res下新建一個anim的目錄,在目錄中新建一個動畫設置的xml文件myanim.xml,代碼如下:
- <?xml version="1.0" encoding="utf-8"?>
- <set xmlns:android="http://schemas.android.com/apk/res/android">
- <alpha
- android:fromAlpha="0.1"
- android:toAlpha="1.0"
- android:duration="2000"
- /> <!-- 透明度的變換 -->
- <!-- fromAlpha屬性爲動畫起始時透明度,toAlpha屬性爲動畫結束時的透明度,
- duration爲動畫持續的時間 -->
- <scale
- android:interpolator="@android:anim/accelerate_decelerate_interpolator"
- android:fromXScale="0.0"
- android:toXScale="1.4"
- android:fromYScale="0.0"
- android:toYScale="1.4"
- android:pivotX="50%"
- android:pivotY="50%"
- android:fillAfter="false"
- android:duration="3000"
- /> <!-- 尺寸的變換 -->
- <!-- interpolator指定一個動畫的插入器,fromXScale屬性爲動畫起始時x座標上的
- 伸縮尺寸,toCScale屬性爲動畫結束時x座標上的伸縮尺寸,fromYScale屬性爲動畫
- 起始時y座標上的伸縮尺寸,toYScale屬性爲動畫結束時y座標上的伸縮尺寸,pivotX
- 和pivotY設置動畫相對於自身的位置,fillAfter表示動畫的轉換在動畫結束後是否
- 被應用 -->
- <translate
- android:fromXDelta="30"
- android:toXDelta="0"
- android:fromYDelta="30"
- android:toYDelta="50"
- android:duration="3000"
- /> <!-- 位置的變換 -->
- <!-- fromXDelta屬性爲動畫起始時x座標上的位置,toXDelta屬性爲動畫結束時x座標
- 上的位置,fromYDelta屬性爲動畫起始時y座標上的位置,toYDelta屬性爲動畫結束時y
- 座標上的位置 -->
- <rotate
- android:interpolator="@android:anim/accelerate_decelerate_interpolator"
- android:fromDegrees="0"
- android:toDegrees="+350"
- android:pivotX="50%"
- android:pivotY="50%"
- android:duration="3000"
- /> <!-- 旋轉變換 -->
- <!-- interpolator同樣爲一個動畫的插入器,fromDegrees屬性爲動畫起始時物件
- 的角度,toDegrees屬性爲動畫結束時物件旋轉的角度 -->
- </set>
然後編寫佈局文件main.xml,代碼如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <ImageView
- android:id="@+id/myImageView"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:src="@drawable/preview"
- />
- </LinearLayout>
其中,preview是放入res/drawable-mdpi的一張圖片,我們以此圖片作爲動畫演示。
最後,在MainActivity.java中編寫加載動畫的代碼:
- package game.test;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.animation.Animation;
- import android.view.animation.AnimationUtils;
- import android.widget.ImageView;
- public class MainActivity extends Activity {
- Animation myAnimation;
- ImageView myImageView;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- myAnimation=AnimationUtils.loadAnimation(this, R.anim.myanim);
- myImageView=(ImageView)this.findViewById(R.id.myImageView);
- myImageView.startAnimation(myAnimation);
- }
- }