-
视图动画(补间动画)
-
帧动画
-
属性动画
1、视图动画
视图动画,也叫Tween(补间)动画。可以在一个视图容器内执行一系列简单变换(位置、大小、旋转,透明度)。可通过XML或Java代码定义,用XML代码定义可读性和可充用行更高。补间动画并未改变View的真实布局属性。
分类:
-
渐变透明度
-
旋转效果
-
尺寸伸缩效果
-
画面转换位置移动效果
-
持有上述动画或的容器
属性:
-
android:detachWallpaper:是否运行在壁纸上
-
android:duration:动画持续时长,ms
-
android:fillAfter:动画结束后是否开始最后状态
-
android:fillBefor/android:fillEnable:动画结束后是否还原到开始状态
-
android:interpolator:插值器(难)
-
android:repeatCount:重复次数
-
android:repeatMode:(reverse|restart)重复模式
-
android:startOffset:调用start后等待开始运行的时间,ms
-
andorid:zAdjustment:(top|bottom|normal)动画运行在Z轴上的位置
Animation类常用方法:
-
reset():重置Animation的初始化
-
cancel():取消Animation动画
-
start():开始Animation动画
-
setAnimationListener(AnimationListener):设置动画监听
-
hasStarted():当前Animation是否开始
-
hasEnded():是否结束
View相关方法:
-
startAnimation(Animation):设置Animation动画
-
clearAnimation():取消当前View正在执行的Animation动画
2、帧动画
没什么好说的
特别注意,AnimationDrawable的start()方法不能在Activity的onCreate方法中调运,因为AnimationDrawable还未完全附着到window上,所以最好的调运时机是onWindowFocusChanged()方法中。
3、属性动画
属性动画通过修改控件的属性值实现动画,区别于视图动画,是真实的修改属性。
属性动画有三种:
-
ViewPropertyAnimator:View自带的属性动画,可以实现简单的动画效果。直接调用
view.animation()获得ViewPropertyAnimator动画对象,直接调用相应的属性动画即可,支持链式调用,不需要显示调用start():viewBinding.tvAlpha.apply { pivotX=0f //设置x轴中心 //先获得ViewPropertyAnimator动画,再设置X轴方法缩放2倍,设置动画时间为5000ms animate().scaleX(2f).duration = 5000 } -
ObjectAnimator:可以对View的任意属性设置动画,如果不是View自带的属性,通过setX/getX为View设置该属性即可。该动画通过
ObjectAnimator.ofXXX()创建,of后面是动画属性类型,第一个参数传入View,第二个参数传入动画名称,再传入动画属性参数。该动画需要显示调用start()才能启动动画://x轴缩放动画,从0.675缩放到1 val scaleXAnimator = ObjectAnimator.ofFloat(viewBinding.tvScale, "scaleX", 0.675f, 1.0f).apply { duration = 800 //动画时间 repeatMode = ValueAnimator.REVERSE //重复样式 interpolator = AnticipateOvershootInterpolator() //差值器 repeatCount = -1 //无限循环 start() } -
TypeEvaluator:一般用于渐变动画,用来计算非基础类型的属性差值。
ObjectAnimator.ofArgb(...)本质就是使用了TypeEvaluator动画。在使用时需要实现TypeEvaluator<T>接口,然后通过ObjectAnimator.setEvaluator(Evaluator)即可:public static ObjectAnimator ofArgb(Object target, String propertyName, int... values) { ObjectAnimator animator = ofInt(target, propertyName, values); animator.setEvaluator(ArgbEvaluator.getInstance()); return animator; } //颜色渐变动画 ObjectAnimator.ofArgb( viewBinding.tvColor, "backgroundColor", resources.getColor(R.color.purple_200), resources.getColor(R.color.purple_700), resources.getColor(R.color.teal_200) ).apply { duration = 2000 repeatMode = ValueAnimator.REVERSE repeatCount = -1 start() }