自定义插值器之前,我们先来看一下系统提供的插值器。为了方便我们来看一个最简单的:LinearInterpolator。
public class LinearInterpolator extends BaseInterpolator implements NativeInterpolatorFactory {
public LinearInterpolator() {
}
public LinearInterpolator(Context context, AttributeSet attrs) {
}
public float getInterpolation(float input) {
return input;
}
/** @hide */
@Override
public long createNativeInterpolator() {
return NativeInterpolatorFactoryHelper.createLinearInterpolator();
}
}
我们再来看看BaseInterpolator源码:
abstract public class BaseInterpolator implements Interpolator {
private @Config int mChangingConfiguration;
/**
* @hide
*/
public @Config int getChangingConfiguration() {
return mChangingConfiguration;
}
/**
* @hide
*/
void setChangingConfiguration(@Config int changingConfiguration) {
mChangingConfiguration = changingConfiguration;
}
}
public interface Interpolator extends TimeInterpolator {
// A new interface, TimeInterpolator, was introduced for the new android.animation
// package. This older Interpolator interface extends TimeInterpolator so that users of
// the new Animator-based animations can use either the old Interpolator implementations or
// new classes that implement TimeInterpolator directly.
}
public interface TimeInterpolator {
/**
* Maps a value representing the elapsed fraction of an animation to a value that represents
* the interpolated fraction. This interpolated value is then multiplied by the change in
* value of an animation to derive the animated value at the current elapsed animation time.
*
* @param input A value between 0 and 1.0 indicating our current point
* in the animation where 0 represents the start and 1.0 represents
* the end
* @return The interpolation value. This value can be more than 1.0 for
* interpolators which overshoot their targets, or less than 0 for
* interpolators that undershoot their targets.
*/
float getInterpolation(float input);
}
可见:input是一个与时间有关的参数,而LinearInterpolator直接返回这一参数,说明:
当前动画的时间进度作为当前动画的进度,因此表现为匀速动画轨迹。
ObjectAnimator alphaAnim = ObjectAnimator .ofFloat(loveImg,"alpha",0.3f,1.0f);
假设:
alphaAnim.setDuration(1000);
alphaAnim.setInterpolator(new LinearInterpolator());
我们想要实现这样一个动画效果,很简单:实现一张图片在1s时间内实现从透明度0.3变化为不透明。
我们来自定义插值器,源码分析可知,实现TimeInterpolator接口即可:
public class MyInterpolator implements TimeInterpolator {
@Override
public float getInterpolation(float input) {
return 1 - input;
}
}
alphaAnim.setInterpolator(new MyInterpolator());
重新设置插值器,发现:图片动画变成了从不透明到透明。
input时间进度为0时,返回值 1 - input = 1,即动画进度执行完毕;
input时间进度为1时,返回值 1 - input = 0,即动画进度刚开始执行。
可见:插值器就是对input时间进度值的数学处理,从而实现时间尺度下不同动画进度效果。