在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();