旋转动画有两种实现方式, 一是xml文件,二是Java代码。
一. 使用xml实现
<ImageView
android:id="@+id/img"
android:layout_centerInParent="true"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/circle"/>
新建anim文件夹,并新建设置参数的文件:rotate_anim.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1000"
android:repeatCount="-1"
android:interpolator="@android:anim/accelerate_interpolator">
<!--
1.android:fromDegrees / android:toDegrees
旋转的起止角度
2.andoird:pivotX / android:pivotY
旋转的中心坐标,距离左上角的偏移量,默认为图片左上角是(0,0)。
若图片大小是200,你可以给(100,100)表示旋转中心点距图片左边50,右边50。若图片的大小未知,可以给百分比。
3.android:interpolator
图片的转动速率
linear_interpolator 匀速转动
accelerate_interpolator 加速转动
decelerate_interpolator 减速转动
4.android:repeatCount
重复的次数,默认为0,必须是int,可以为-1表示不停止
5.android:duration
转一圈所需时间,单位为毫秒。可以用来计算速度
6.android:startOffset
在调用start函数之后等待开始运行的时间,单位为毫秒,若为10,表示10ms后开始运行
7.android:repeatMode
重复的模式,默认为restart,即重头开始重新运行,可以为reverse即从结束开始向前重新运行。
在android:repeatCount大于0或为infinite时生效。
-->
</rotate>
</rotate>
最后,使用rotate_anim.xml文件,并开始动画。
Animation an = AnimationUtils.loadAnimation(this, R.anim.rotate_anim);
img = findViewById(R.id.img);
img.startAnimation(an);
二. 使用Java代码
img = findViewById(R.id.img);
RotateAnimation animation = new RotateAnimation(0, 360,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);//围绕自身的中心旋转
animation.setInterpolator(new LinearInterpolator());//匀速旋转
animation.setDuration(1000);
animation.setRepeatCount(-1);//无限重复
img.startAnimation(animation);
参考: