AnimationDrawable代表一个动画,Android 既支持传统的逐帧动画(类 似于电影方式,一张图片、一张图片地切换),也支持通过平移、变换计算出来的补间动画。
下面以补间动画为例来介绍如何定义 AnimationDrawable 资源,定义补间动画的 XML 资 源文件以<set.../>元素作为根元素,该元素内可以指定如下 4 个元素:
- alpha:设置透明度的改变。
- scale:设置图片进行缩放改变。
- translate:设置图片进行位移变换。
- rotate:设置图片进行旋转。
定义动画的 XML 资源应该放在/res/anmi 路径下,当使用 ADT 创建一个 Android 应用时, 默认不会包含该路径,开发者需要自行创建该路径。
定义补间动画的思路很简单:设置一张图片的开始状态(包括透明度、位置、缩放比、 旋转度)、并设置该图片的结束状态(包括透明度、位置、缩放比、旋转度),再设置动画的 持续时间,Android 系统会使用动画效果把这张图片从开始状态变换到结束状态。
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/image" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/java" /> <Button android:id="@+id/bn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始动画" /> </LinearLayout>
my_anim.xml
图片将会变宽为原来的1.4倍,同时高度变为原来的0.6倍,向上向右移动。
<?xml version="1.0" encoding="UTF-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/linear_interpolator" android:duration="5000"> <!-- 定义缩放变换 --> <scale android:fromXScale="1.0" android:toXScale="1.4" android:fromYScale="1.0" android:toYScale="0.6" android:pivotX="50%" android:pivotY="50%" android:fillAfter="true" android:duration="2000" /> <!-- 定义位移变换 --> <translate android:fromXDelta="10" android:toXDelta="130" android:fromYDelta="30" android:toYDelta="-80" android:duration="2000" /> </set>
AnimationDrawable.java
package org.crazyit.res; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageView; /** * Description: * <br/>site: <a href="http://www.crazyit.org">crazyit.org</a> * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class AnimationDrawable extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ImageView image = (ImageView)findViewById(R.id.image); // 加载动画资源 final Animation anim = AnimationUtils.loadAnimation(this, R.anim.my_anim); // 设置动画结束后保留结束状态 anim.setFillAfter(true); Button bn = (Button) findViewById(R.id.bn); bn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // 开始动画 image.startAnimation(anim); } }); } }