Android 围绕中心旋转动画
一 简介
开发中遇到扫描蓝牙动画需求,如下图所示:
因此以下简单记录一下,方便以后使用。
Android 平台提供了两类动画,一类是 Tween 动画,即通过对场景里的对象不断做图像变换(平移、缩放、旋转)产生动画效果;第二类是 Frame 动画,即顺序播放事先做好的图像,跟电影类似。
二 应用
1.xml中写好需要旋转的view。
我用了一个ConstraintLayout布局将要旋转的部分包括起来。
2.定义rotate旋转效果
在res/anim文件夹下新建rotation_animation.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:duration="1500"
android:fromDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="-1"
android:repeatMode="restart"
android:toDegrees="0" />
<!--
参数的含义
duration:表示从android:fromDegrees转动到android:toDegrees所花费的时间
fromDegrees="0": 起始的角度度数
toDegrees="359" : 结束的角度度数
pivotX="50%:旋转中心距离view的左顶点为50%距离,
pivotY="50%: 距离view的上边缘为50%距离
repeatCount="-1":重复次数,-1为一直重复
repeatMode="restart":重复模式,restart从头开始重复,reverse即从结束开始向前重新运行
实际效果为顺逆时针交替
未用到属性:
android:interpolator表示变化率,但不是运行速度。一个插补属性,
可以将动画效果设置为加速,减速,反复,反弹等。默认为开始和结束慢中间快,
android:startOffset 在调用start函数之后等待开始运行的时间,单位为毫秒,
若为10,表示10ms后开始运行
-->
</set>
3.在代码中设置应用
//开始旋转
Animation animation = AnimationUtils.loadAnimation(this,R.anim.rotation_animation);
LinearInterpolator lin = new LinearInterpolator();//设置动画匀速运动
animation.setInterpolator(lin);
clRotation.startAnimation(animation);
//停止旋转
clRotation.clearAnimation();
- setInterpolator表示设置旋转速率。LinearInterpolator为匀速效果,Accelerateinterpolator为加速效果、DecelerateInterpolator为减速效果。
- 停止旋转最好用代码设置,也可以强制设置rotate转动多少圈,前者更好。
4.横竖屏切换导致旋转中心偏移解决办法
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (animation != null && clRotation != null && animation.hasStarted()) {
clRotation.clearAnimation();
clRotation.startAnimation(animation);
}
}