自定义插值器

前言

相信大家都用过补间动画(Tween Animation),那么对插值器(Interpolator)应该也不陌生,虽然SDK已经提供了一些Interpolator的实现类,但是如果你想实现一些特定效果,那就得自己自定义了


介绍

先简单介绍一下Interpolator,他会根据类型的不同,选择不同的算法计算出在补间动画期间所需要动态插入帧的密度和位置,Interpolator负责控制动画的变化速度,使得动画效果能够以匀速,变速,抛物线等各种速度进行变化。

好了介绍结束,接下来进入正题。

Interpolator的实现

我们先来看看源码,看LinearInterpolator是怎么实现的:

/**
 * An interpolator where the rate of change is constant
 */
@HasNativeInterpolator
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();
    }
}

再来看看稍微复杂一点的AccelerateDecelerateInterpolator是怎么实现的:

/**
 * An interpolator where the rate of change starts and ends slowly but
 * accelerates through the middle.
 */
@HasNativeInterpolator
public class AccelerateDecelerateInterpolator extends BaseInterpolator
        implements NativeInterpolatorFactory {
    public AccelerateDecelerateInterpolator() {
    }

    @SuppressWarnings({"UnusedDeclaration"})
    public AccelerateDecelerateInterpolator(Context context, AttributeSet attrs) {
    }

    public float getInterpolation(float input) {
        return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
    }

    /** @hide */
    @Override
    public long createNativeInterpolator() {
        return NativeInterpolatorFactoryHelper.createAccelerateDecelerateInterpolator();
    }
}

好了,聪明的你一定发现了,这两种Interpolator主要的不同就在于float getInterpolation(float input)的不同,不同的插值器,你实现不同的getInterpolation就行了。

float getInterpolation(float input)的入参是一个0.0~1.0的值,返回值可以小于0.0,也可以大于1.0。这个方法代表了插值器的运动逻辑,你看LinearInterpolator是常量速率的插值器,所以输入什么就返回什么;AccelerateDecelerateInterpolator是开始和结束的时候比较快,中间比较慢,所以它用的逻辑是余弦函数,你们看看余弦函数的图就可以理解了。

自定义Interpolator

经过了前面的铺垫,我们知道,我们之需要实现float getInterpolation(float input)就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值