旋转动画(RotateAnimation)简介
以指定的坐标点为中心,使控件做圆周运动,称之为旋转。android提供了系统级别的类来帮助我们完成旋转动画。
旋转动画的属性
旋转动画有部分属性与平移和缩放动画相同,同时也有一些特有的属性,旋转动画的属性如下:
属性 | 描述 |
---|---|
fromDegrees | 开始角度,位置0,相当于缩放动画的fromXScale或fromYScale |
toDegrees | 结束角度,正数表示顺时针,负数表示逆时针,相当于缩放动画的toXScale或toYScale |
detachWallpaper | 是否在壁纸上运行 |
zAdjustment | 表示旋转的内容在Z轴的位置,默认normal,top 最顶层,bottom 最底层 |
repeatMode | 同平移或缩放动画 |
repeatCount | 同平移或缩放动画 |
pivotX | 旋转中心点的X轴坐标,可以是浮点数或者百分比 |
pivotY | 旋转中心点Y轴坐标,可以是浮点数或者百分比 |
旋转动画的实现方式
所有的补间动画都可以通过xml和代码两种方式创建,旋转动画也不例外。 接下来同样通过一个demo来讲解一下这两种方式
旋转动画demo
这个demo要实现的效果是通过两个旋转动画来模拟齿轮关联转动的效果,效果如下:
首先通过xml方式实现,xml方式主要有两步:
1. 创建两个动画文件rotate.xml和rotate2.xml
rotate.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2500"//时长2500ms
android:shareInterpolator="false">//不共享插值器
<rotate android:fromDegrees="0"//起始角度
android:toDegrees="360"//结束角度,正数代表顺时针旋转
android:pivotX="50%"//起始位置x坐标,50%表示控件的横向中心位置
android:pivotY="50%"//起始位置y坐标,50%表示控件的纵向中心位置
android:repeatCount="infinite"//无限次循环
android:interpolator="@android:anim/linear_interpolator"//匀速运动插值器
/>
</set>
rotate2.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2500"
android:shareInterpolator="false">
<rotate android:fromDegrees="0"
android:toDegrees="-360"//负数表示逆时针旋转
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:interpolator="@android:anim/linear_interpolator"
/>
</set>
2. 使用AnimationSet加载两个xml文件并分别执行
Animation animation = AnimationUtils.loadAnimation(this,R.anim.rotate);
Animation animation2 = AnimationUtils.loadAnimation(this,R.anim.rotate2);
AnimationSet set = new AnimationSet(false);
set.addAnimation(animation);
set.addAnimation(animation2);
iv_rotate.startAnimation(set.getAnimations().get(0));
iv_rotate2.startAnimation(set.getAnimations().get(1));
通过Java代码的方式实现
Animation animation = new RotateAnimation(0,360,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(2500);
animation.setRepeatCount(Animation.INFINITE);//无限循环
animation.setInterpolator(new LinearInterpolator());//匀速运动插值器
Animation animation1 = new RotateAnimation(0,-360,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
animation1.setDuration(2500);
animation1.setRepeatCount(Animation.INFINITE);//无限循环
animation1.setInterpolator(new LinearInterpolator());//匀速运动插值器
iv_rotate.startAnimation(animation);
iv_rotate2.startAnimation(animation1);
旋转动画每一次结束之后会有一个小小停顿的现象,这个时候可以将toDegress和duration放大1000倍或者更大,这就相当于把每次的停顿都进行了相同倍数的弱化,从视觉上就感受不到停顿了。