本文主要介绍Android中实现图片不停旋转的一种简单方式
1、先定义一个 ImageView 图片控件
<ImageView
android:id="@+id/iv_loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon_jz"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
2、res下建立一个动画文件夹anim
3、anim文件夹下面建立名称为:rotaterepeat动画xml文件
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<rotate
android:fromDegrees="0"
android:toDegrees="359"
android:duration="1000"
android:repeatCount="-1"
android:pivotX="50%"
android:pivotY="50%"
/>
</set>
含义表示从0到359度开始循环旋转,
0-359(若设置成360在停止时会出现停顿现象)度旋转所用时间为500ms,
旋转中心距离view的左顶点为50%距离,距离view的上边缘为50%距离,即正中心,
具体每个含义见下面的具体属性介绍。
循环运行
android:fromDegrees="0"
android:toDegrees="359"
android:repeatCount="-1"
android:repeatCount="-1"即表示循环运行,
配合上android:fromDegrees=“0” android:toDegrees="360"表示不间断
4、在activity 中使用动画
ImageView iv_loading = findViewById(R.id.iv_loading);
Animation mAnimation = AnimationUtils.loadAnimation(this, R.anim.rotaterepeat);
LinearInterpolator lin = new LinearInterpolator();
mAnimation.setInterpolator(lin);
iv_loading.startAnimation(mAnimation);
setInterpolator 表示设置旋转速率。
LinearInterpolator 为匀速效果,
Accelerateinterpolator 为加速效果、
DecelerateInterpolator 为减速效果
开始旋转
iv_loading.startAnimation(mAnimation);
停止旋转
iv_loading.clearAnimation();
5、其中的属性意义如下
android:fromDegrees
起始的角度度数
android:toDegrees
结束的角度度数,负数表示逆时针,正数表示顺时针。如10圈则比android:fromDegrees大3600即可
android:pivotX
旋转中心的X坐标
浮点数或是百分比。浮点数表示相对于Object的左边缘,如5; 百分比表示相对于Object的左边缘,如5%; 另一种百分比表示相对于父容器的左边缘,如5%p; 一般设置为50%表示在Object中心
android:pivotY
旋转中心的Y坐标
浮点数或是百分比。浮点数表示相对于Object的上边缘,如5; 百分比表示相对于Object的上边缘,如5%; 另一种百分比表示相对于父容器的上边缘,如5%p; 一般设置为50%表示在Object中心
android:duration
表示从android:fromDegrees转动到android:toDegrees所花费的时间,单位为毫秒。可以用来计算速度。
android:interpolator
表示变化率,但不是运行速度。一个插补属性,可以将动画效果设置为加速,减速,反复,反弹等。
默认为开始和结束慢中间快,
android:startOffset
在调用start函数之后等待开始运行的时间,单位为毫秒,若为10,表示10ms后开始运行
android:repeatCount
重复的次数,默认为0,必须是int,可以为-1表示不停止
android:repeatMode
重复的模式,默认为restart,即重头开始重新运行,可以为reverse即从结束开始向前重新运行。
在android:repeatCount大于0或为infinite时生效
android:detachWallpaper
表示是否在壁纸上运行
android:zAdjustment
表示被animated的内容在运行时在z轴上的位置,默认为normal。
normal
保持内容当前的z轴顺序
top
运行时在最顶层显示
bottom
运行时在最底层显示