Android 里动画从用途上讲,可以分为三类View Animation(View动画)又称 Tween Animation(补间动画)、Drawable Animation(帧动画) 和 Property Animation(属性动画)。 这篇文章,我就介绍一下这三种类型的动画。
目录:
(一)View动画
View动画是基于View的渐变动画,只改变了View的绘制效果,View的实际属性值并未改变。
View动画的对象是View,它支持4种动画效果:
TranslateAnimation(平移动画)
ScaleAnimation(缩放动画)
RotateAnimation(旋转动画)
AlphaAnimation(透明度动画)
并提供了AnimationSet动画集合。实现原理是每次绘图时View所在的ViewGroup中的dispathDraw,流程如下图:
除了这四种典型的动画效果外,帧动画本质上也属于View动画。但是帧动画的表现形式和这4种动画不太一样,因此通常单拎出来归为一类。
这四种动画既可以通过XML来定义,也可以通过代码来动态创建。
使用XML之前我们首先需要创建XML文件,路径为:res/anim/filename.xml。
1. 透明度动画
代码实现:AlphaAnimation animation = new AlphaAnimation(0, 1);// 透明度0变化到透明度为1
animation.setDuration(1000);// 动画执行时间1s
textView.startAnimation(animation);
XML实现:
android:duration="1000"
android:fromAlpha="0"
android:interpolator="@android:anim/accelerate_interpolator"
android:repeatCount="3"
android:fillAfter="true"
android:repeatMode="restart"
android:toAlpha="1" />
2. 旋转动画
代码实现:RotateAnimation animation = new RotateAnimation(0, 360, 100, 100);
animation.setDuration(1000);
animation.setFillAfter(true); // 设置保持动画最后的状态
animation.setInterpolator(new AccelerateInterpolator()); // 设置插入器
textView.startAnimation(animation);
还可以通过系统提供参数来控制动画
new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
xml实现:
android:duration="1000"
android:fromDegrees="0.0"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50.0%"
android:pivotY="50.0%"
android:repeatCount="infinite"
android:toDegrees="360.0">
参数
说明fromDegrees
为动画起始时的旋转角度,此角度是当前为0及360,设置其他值则先跳至该角度的位置再由from - to的值: 负则正向转,正则反向转
toDegrees
为动画旋转到的角度
pivotXType
为动画在X轴相对于物件位置类型
pivotXValue
为动画相对于物件的X坐标的开始位置,此值是以本身原始位置为原点,即如设为20%p,则向右移动父控件的20%位移,为负数则向左移
pivotYType
为动画在Y轴相对于物件位置类型
pivotYValue
为动画相对于物件的Y坐标的开始位置,此值是以本身原始位置为原点,即如设为20%p,则向下移动父控件的20%位移,为负数则向上移
3. 位移动画
代码实现:TranslateAnimation translateAnimation = new TranslateAnimation(0, 200, 0, 200);
translateAnimation.setDuration(1000);
textView.startAnimation(translateAnimation);
xml实现:
android:duration="1000"
android:fillAfter="true"
android:fromXDelta="0"
android:fromYDelta="0"
android:repeatCount="3"
android:toXDelta="200"
android:toYDelta="000">
参数
说明fromXDelta
为动画起始时 X坐标上的移动位置
toXDelta
为动画结束时 X坐标上的移动位置
fromYDelta
为动画起始时Y坐标上的移动位置
toYDelta
为动画结束时Y坐标上的移动位置
4. 缩放动画
代码实现:ScaleAnimation animation = new ScaleAnimation(0,1,0,1);
animation.