Android支持的动画包括
- 逐帧动画(就是一张一张图片的切换)
- 补间动画(通过平移、变换计算得到)
下面就由我们来通过补间动画来演示下Android如何通过定义AnimationDrawable资源来定义动画,并用它来进行有趣的动画设计。效果如图所示
AnimationDrawable的XML源文件的根元素为< set…/>
第一步,我们需要在/res/anmi/路径下定义我们好我们的动画的XML文件(默认AS是不包含此路径的,需要开发者自行创建该路径。
通过设置一张图片的开始状态(包括透明度、位置、缩放比、旋转度),再设置该图片的结束状态(包括透明度、位置、缩放比、旋转度),再设置动画的持续时间,Android就会自动就把该图片从开始状态变换到结束状态
这是我定义的在/res/anim/my_anim的文件
<?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>
第二步我们定义下我们的activity_main.xml里面的控件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:src="@mipmap/ic_launcher" />
<Button
android:id="@+id/bn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动动画"/>
</LinearLayout>
最后就是加载动画并且启动它了。
setContentView(R.layout.activity_main);
final ImageView imageView = (ImageView) findViewById(R.id.image);
//加载动画资源
final Animation animation = AnimationUtils.loadAnimation(this,R.anim.my_anim);
//设置动画结束后保留结束状态
animation.setFillAfter(true);
Button bn = (Button)findViewById(R.id.bn);
bn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
//开始动画
imageView.startAnimation(animation);
}
});