Android 动画 ValueAnimator(二)

一.概述

在上篇中我们讲了valueAnimator的基本使用,这篇我们来看看如何使用插值器以及自定义插值器。
什么是插值器,简单给大家描述一下,插值器就是定义了动画在整个过程中进度的数值是如何变化的,就像骑自行车一样,有加速的,减速的,匀速的等等。
1.使用插值器
我们以BounceInterpolator(弹跳)插值器为例子,看一下插值器的效果:
这里写图片描述

我们可以看到,动画在结束的位置弹了几次。这就是BounceInterpolator的效果。

  textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "点击了", Toast.LENGTH_SHORT).show();
            }
        });
         animator = ValueAnimator.ofInt(0,400);
        animator.setInterpolator(new BounceInterpolator());
        animator.setDuration(1000);

2.自定义插值器

在自定义插值器之前,我们看看系统的插值器是怎么实现的,我们以比较简单的LinearInterpolator为例,这是一个线性插值器。

public class LinearInterpolator implements Interpolator {

    public LinearInterpolator() {
    }

    public LinearInterpolator(Context context, AttributeSet attrs) {
    }

    public float getInterpolation(float input) {
        return input;
    }
}

LinearInterpolator 实现了Interpolator 接口,而Interpolator接口继承了TimeInterpolator 接口,重写了getInterpolation方法。

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);
}

下面重点对getInterpolation(float input)这个方法进行一下介绍
float类型的参数input代表当前动画的进度,值从0到1,0代表动画开始,1代表动画结束。
返回值代表实际显示的值,可以小于0也可以大于1,小于0代表小于开始位置,大于1代表大于结束位置。
在LinearInterpolaor中我们可以看到getInterpolation直接返回了输入参数input,这就代表当前的值和动画的执行进度是一致的。

下面我们看看怎么自定义插值器
和系统一样,我们让定义的插值器继承TimeInterpolator

public class MyInterpolator implements TimeInterpolator {
    @Override
    public float getInterpolation(float input) {
        return 1-input;
    }
}

然后在代码中使用我们定义好的插值器

  animator.setInterpolator(new MyInterpolator());

这里写图片描述

在getInterpolation方法里面我们返回了1减去input,这就代表当前的位置和动画的执行进度刚好是相反的,意思就是当动画开始的时候,我们让textview在结束的位置,当动画结束的时候,我们让textview在开始的位置。

如果大家想要定义更负责的插值器,那就需要很好的数学基础了,大家可以看看系统的插值器是怎么实现的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值