美文网首页
如何让你的Android Lottie动画反向播放

如何让你的Android Lottie动画反向播放

作者: 晖仔Milo | 来源:发表于2022-06-22 10:06 被阅读0次

前言

lottie可以快速帮我们完成一些高难度的动画,从而有效提高了我们动画开发效率,但经常从设计手中提供过来的lottie需要我们反向播放,比如“关注/取关”,关注播放普通动画,取关则逆向播放一遍。

问题

查阅lottie的api,我们发现其并未直接提供反向播放的api
那项目中我们如何实现呢?

解决

1、查阅文档,方发有一个控制进度的api,如下

  public void setProgress(@FloatRange(from = 0f, to = 1f) float progress) {
    lottieDrawable.setProgress(progress);
  }

那我们能不能直接通过进度控制来达到我们的目的了,答案是可以的。
我们只需要结合ValueAnimation就可以轻松的实现反向播放控制。

eg:

    private ValueAnimator valueAnimator;
    private ValueAnimator.AnimatorUpdateListener animatorUpdateListener;

    private void playStartLottieView() {
        releaseAnimatorUpdateListener();
        valueAnimator = ValueAnimator.ofFloat(0f, 1.0f);
        animatorUpdateListener = new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                binding.lottieView.setProgress((float) animation.getAnimatedValue());
            }
        };
        valueAnimator.addUpdateListener(animatorUpdateListener);
        valueAnimator.start();
    }

    private void playStopLottieView() {
        releaseAnimatorUpdateListener();
        valueAnimator = ValueAnimator.ofFloat(1f, 0f);
        animatorUpdateListener = new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                binding.lottieView.setProgress((float) animation.getAnimatedValue());
            }
        };
        valueAnimator.addUpdateListener(animatorUpdateListener);
        valueAnimator.start();
    }


    private void releaseAnimatorUpdateListener() {
        if (valueAnimator != null && animatorUpdateListener != null) {
            valueAnimator.removeUpdateListener(animatorUpdateListener);
        }
    }

扩展

当然,如果你项目中仅仅只需要重复播放正向+反向动画,是可以直接调用lottie-api直接实现的

        binding.lottieView.setRepeatCount(-1);
        binding.lottieView.setRepeatMode(LottieDrawable.REVERSE);
        binding.lottieView.playAnimation();

这篇文章就讲到这里啦。

相关文章

网友评论

      本文标题:如何让你的Android Lottie动画反向播放

      本文链接:https://www.haomeiwen.com/subject/epgyvrtx.html