Animation 与 Animator
动画我们一般分为传统动画Animation和属性动画Animator
Animation动画的原理是不断调用onDraw方法不断的重新绘制控件,可以实现 旋转,位移,缩放,透明度。
属性动画顾名思义,是不断调用控件属性的get set方法去真实地改变控件的属性
相对于属性动画,Animation动画只能改变控件的显示,不能真正地改变控件的属性,对于需要交互的控件是不适用的
所以 Android3.0引入了属性动画
Animator简单使用
1.简单的平移示例
translationX表示控件在X方向上的偏移量,初始值一般为0,这样动画起始不会突兀
float可以是多个参数,用,隔开,动画分多段进行
ObjectAnimator.ofFloat(button,"translationX",0f,200f).setDuration(1000).start();
translationX translationY rotation rotationX rotationY scaleX scaleY alpha
rotationX是绕X轴旋转,(还有那么点立体的感觉)
2.多个动画同时start,其实是一个异步的过程
ObjectAnimator.ofFloat(imageView,"rotation",0f,360f).setDuration(1000).start();
ObjectAnimator.ofFloat(imageView,"translationX",0f,200f).setDuration(1000).start();
ObjectAnimator.ofFloat(imageView,"translationY",0f,200f).setDuration(1000).start();
这三个动画效果是同时进行的
3.也可以使用PropertyValuesHolder先将要同时进行的动画属性名与属性值保存起来,使用ofPropertyValuesHolder方法展示动画,
效果与以上相同,并且,该方法在性能上是有所优化的
PropertyValuesHolder p1=PropertyValuesHolder.ofFloat("rotation",0f,360f);
PropertyValuesHolder p2=PropertyValuesHolder.ofFloat("translationX",0f,200f);
PropertyValuesHolder p3=PropertyValuesHolder.ofFloat("translationY",0f,200f);
ObjectAnimator.ofPropertyValuesHolder(imageView,p1,p2,p3).setDuration(1000).start();
ObjectAnimator animator1=ObjectAnimator.ofFloat(imageView,"rotation",0f,360f);
ObjectAnimator animator2=ObjectAnimator.ofFloat(imageView,"translationX",0f,200f);
ObjectAnimator animator3=ObjectAnimator.ofFloat(imageView,"translationY",0f,200f);
AnimatorSet set=new AnimatorSet();
set.playTogether(animator1,animator2,animator3);
set.setDuration(1000);
set.start();
但是AnimatorSet有丰富的功能,例如,替换playTogether方法为
set.playSequentially(animator1,animator2,animator3);
这三个动画就会按先后顺序一一执行,每个动画执行时间都是1秒
也可以使用play, with, after 来进行单独的执行顺序的控制
with表示同时,即先同时执行2,3,然后执行1,每步都是1s
set.play(animator2).with(animator3);
set.play(animator1).after(animator2);
Animator动画监听事件
ObjectAnimator animator=ObjectAnimator.ofFloat(imageView,"rotation",0f,360f);
animator.setDuration(1000);
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
animator.start();
大部分时候也许只需要监听onAnimationEnd,可以通过添加AnimatorListenAdapter,只监听需要监听的事件
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
//方法体
}
});
可以使用插值器,给动画增加更多 多变的效果
安卓内置了很多插值器,基本能满足使用需求
AccelerateDecelerateInterpolator, AccelerateInterpolator, AnticipateInterpolator, AnticipateOvershootInterpolator, BaseInterpolator, BounceInterpolator, CycleInterpolator, DecelerateInterpolator, FastOutLinearInInterpolator, FastOutSlowInInterpolator, LinearInterpolator,
LinearOutSlowInInterpolator, OvershootInterpolator, PathInterpolator
animator.setInterpolator(new BounceInterpolator());
以下是常用插值器的效果一览图,横轴是时间,纵轴是变化量
以上内容整理自慕课网