RotateAnimation 用来创建旋转效果的动画,同样也有两种方式创建。
同样的,我们可以在 XML 当中描述一些属性,然后再在 Java 代码中实例化该动画对象。
RotateAnimation 的属性都包含在 <rotate>
标签当中,可用的属性有:
示例:
anim/anim_rotate.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="2000"
android:repeatCount="-1"
android:repeatMode="reverse"/>
MainActivity.java
public class MainActivity extends Activity {
private ImageView imageView;
private Button start, stop;
private RotateAnimation animation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.gif);
start = findViewById(R.id.startAnimation);
stop = findViewById(R.id.stopAnimation);
animation = (RotateAnimation) AnimationUtils.loadAnimation(this,R.anim.anim_rotate);
}
@Override
protected void onStart() {
super.onStart();
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView.startAnimation(animation);//启动动画
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// animation.cancel();//取消动画
imageView.clearAnimation();
}
});
}
}
通过三个构造方法可以创建出 RotateAnimation 对象:
也没啥好讲的,和 XML 属性一样,还有就是确定位置的类型,之前几个动画类里都讲过
示例:
public class MainActivity extends Activity {
private ImageView imageView;
private Button start, stop;
private Animation animation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.gif);
start = findViewById(R.id.startAnimation);
stop = findViewById(R.id.stopAnimation);
animation = new RotateAnimation(0, 90);
animation.setDuration(3000);
animation.setRepeatCount(-1);
animation.setRepeatMode(Animation.REVERSE);
animation.setStartOffset(1000);
}
@Override
protected void onStart() {
super.onStart();
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView.startAnimation(animation);//启动动画
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// animation.cancel();//取消动画
imageView.clearAnimation();
}
});
}
}
更多内容请看这里: