在Android中,Interpolator(插值器)用于改变动画的速度曲线。要获取一个Interpolator实例,你可以使用以下几种方法:
// 获取线性插值器
Interpolator linearInterpolator = android.view.animation.LinearInterpolator.getInstance();
// 获取加速插值器
Interpolator accelerateInterpolator = android.view.animation.AccelerateInterpolator.getInstance();
// 获取减速插值器
Interpolator decelerateInterpolator = android.view.animation.DecelerateInterpolator.getInstance();
// 获取加速减速插值器
Interpolator accelerateDecelerateInterpolator = android.view.animation.AccelerateDecelerateInterpolator.getInstance();
// 获取弹性插值器
Interpolator elasticInterpolator = android.view.animation.ElasticInterpolator.getInstance();
要创建自定义插值器,你需要实现TimeInterpolator
接口并重写getInterpolation(float input)
方法。例如,以下是一个简单的自定义插值器,它在动画开始时加速,然后在结束时减速:
public class CustomInterpolator implements TimeInterpolator {
private float start;
private float end;
public CustomInterpolator(float start, float end) {
this.start = start;
this.end = end;
}
@Override
public float getInterpolation(float input) {
if (input < start) {
return 0;
} else if (input >= end) {
return 1;
} else {
return start + (end - start) * (float) Math.pow(input - start, 2);
}
}
}
要使用自定义插值器,只需创建一个实例并将其传递给ObjectAnimator
或ValueAnimator
:
CustomInterpolator customInterpolator = new CustomInterpolator(0, 1);
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "translationX", 0f, 100f);
objectAnimator.setInterpolator(customInterpolator);
objectAnimator.setDuration(1000);
objectAnimator.start();