RotateAnimation(旋转动画)
今天通过指定一个动画效果(类似钟摆的动画)来讲解RotateAnimation的用法。ScaleAnimation 、 AlphaAnimation、 TranslateAnimation 的用法请参照相关文章。
先看一下下面这个坐标系,如果toDegrees < fromDegrees , 则动画是逆时真旋转的。RotateAnimation一个简单的构造函数RotateAnimation(FromDegrees,toDegrees)便可实现旋转动画。
好了,下面就来完成一个类似钟摆的动画。
1、在res/anim目录下创建文件 rotate_anim.xml , 内容如下:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="500"
android:fromDegrees="-90"
android:pivotX="50%"
android:pivotY="0"
android:repeatCount="-1"
android:repeatMode="reverse"
android:toDegrees="90" >
</rotate>
其中,动画时长 android:duration="500" : 完成一次动画500毫秒。
android:pivotX=“50%”: 图片的中点。
android:pivotY="0": Y轴没有偏移量。 pivotX和pivotY确认的坐标就是 (viewX + vWidth/2 , viewY)。
android:fromDegrees , android:toDegrees , -90 度到 90 度 。
2、在res/layout目录下创建 rotate_anim_layout.xml ,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/tweened_rotate_img"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:src="@drawable/ting_frame_0"
android:contentDescription="@string/app_name"
android:adjustViewBounds="true"
android:layout_gravity="center" />
</LinearLayout>
该文件中使用到了名为ting_frame_0的图片,请准备好。
3、创建用于显示动画的activity , rotateAnimActivity.java 内容如下:
import android.app.Activity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class RotateAnimActivity extends Activity {
Animation mRotateAnim;
private ImageView mRotateImg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rotate_anim_layout);
init();
mRotateAnim = AnimationUtils.loadAnimation(this, R.anim.rotate_anim);
}
private void init() {
mRotateImg = (ImageView) findViewById(R.id.tweened_rotate_img);
}
@Override
protected void onPause() {
super.onPause();
if (mRotateAnim != null) {
mRotateAnim.cancel();
}
}
@Override
protected void onResume() {
super.onResume();
if (mRotateAnim != null) {
mRotateImg.startAnimation(mRotateAnim);
}
}
}
AnimationUtils.loadAnimation(this, R.anim.rotate_anim); 加载资源
mRotateImg.startAnimation(mRotateAnim); 启动动画
ok,大功告成!