ObjectAnimator
ObjectAnimator继承于ValueAnimator,通常我们更多的去使用ObjectAnimator。ObjectAnimator中最常用的方法有ofInt(),ofFloat,ofObject()方法。它们都能返回一个ObjectAnimator对象。通过使用ObjectAnimator,短短几行代码就能够实现一个动画
ofFloat()常用参数:
ofFloat(Object target, String propertyName, float... values)
这里target可以是任何对象,propertyName是属性名有rotation,alpha,translationX等,第三个参数是针对第二个属性的渐变值。
public void startAnimation(){
ObjectAnimatior animator=ObjectAnimator.ofFloat(imageView,"rotation",0f,360f); //让imageView沿着中心360度旋转
animator.setDuration(1000); //动画的执行时间
animator.start();
}
下面列举一些常用属性:
ObjectAnimator animator=ObjectAnimator.ofFloat(imageView,"scaleY",1f,2f,1f); //imageView沿着Y轴拉伸至俩倍再到一倍
ObjectAnimator animator=ObjectAnimator.ofFloat(imageView,"scaleX",1f,2f,1f); imageView沿着X轴拉伸至俩倍再到一倍
ObjectAnimator animator=ObjectAnimator.ofFloat(imageView,"rotationX",0f,360f); //imageView以X轴为轴心选择360度,rotationY同理
ObjectAnimator animator=ObjectAnimator.ofFloat(imageView,"alpha",0f,1f); //imageView 颜色淡入由0%到100%
ObjectAnimator animator=ObjectAnimator.ofFloat(imageView,"translationX",0f,-500f,0f); //转变imageView 的X坐标值。同理translationY。
AnimatorSet类
AnimatorSet类允许你同时编排多个动画
public void startAnimation(){
ObjectAnimator animator=ObjectAnimator.ofFloat(imageView,"alpha",1f,0f,1f);
animator.setDuration(1000);
ObjectAnimator rotation=ObjectAnimator.ofFloat(imageView,"rotation",0f,360f);
ObjectAnimator translationX=ObjectAnimator.ofFloat(imageView,"translationX",0f,500f,0f);
ObjectAnimator translationY=ObjectAnimator.ofFloat(imageView,"translationY",0f,500f,0f);
AnimatorSet animatorSet=new AnimatorSet();
animatorSet.play(animator)
.with(rotation)
.with(translationX)
.with(translationY);
animatorSet.setDuration(5000);
animatorSet.start();
}
如上所示,可以同时实现X,Y轴的移动并选择淡入淡出。
实现抛物线:
(水平方向100px/s,所以x=100*t*fraction,y=0.5/a*t*t a取200px/s
public void startAnimation(){
animator=new ValueAnimator();
animator.setDuration(5000);
animator.setObjectValues(new PointF(0,0));
animator.setInterpolator(new LinearInterpolator());
animator.setEvaluator(new TypeEvaluator<PointF>() {
@Override
public PointF evaluate(float fraction, PointF startValue, PointF endValue) {
PointF pointF=new PointF();
pointF.x=100*fraction*3;
pointF.y=0.5f*200*(3*fraction)*(3*fraction);
return pointF;
}
});
animator.start();
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
PointF pointF=(PointF) animator.getAnimatedValue();
imageView.setX(pointF.x);
imageView.setY(pointF.y);
}
});
}