Lottie 概述
https://airbnb.design/lottie/ Lottie 官网
Lottie 是一个支持多端展示的动效库,相对于 OpenGL 、动画、GIF Lottie 有着他独有的一些优点和优势,例如对比原生动画 api 直接的就节省了开发很大程度上的编码工作量。只需要设计人员通过 AE 去到处他想要的效果即可,对比于 GIF GIF 相对效果差支持 8 位颜色,另外 Lottie 对于包体力增量也有很好的控制,非常值得我们去尝试和应用。
下方链接列出了 Lottie 所支持的设备平台以及功能
https://airbnb.io/lottie/#/supported-features Lottie 官网支持功能
Lottie 中文文档
https://www.yuque.com/lottie/document/readme
Lottie 当然可能也有他的一些不足点,已经有先驱给我们做了一些记录。如果我们开发过程中遇到一些 Lottie 的问题可以翻阅
https://zhuanlan.zhihu.com/p/59794085
Lottie 应用
Android 版本的 Lottie 目前迭代到的最新 release 版本是 3.7.0 (2021年4月),我们将居理买房 App 中的 Lottie 升级到这个版本然后对其做一个实践
<com.airbnb.lottie.LottieAnimationView
android:id="@+id/iv_tab_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
我们改造代码,将我们熟悉的 ImageView 修改为 LottieAnimationView ,实际上 LottieAnimationView 也继承自 ImageView。
LottieAnimationView 在 xml 当中支持相当对的自定义属性,例如指定加载的 Lottie 动效文件
大多数自定义属性都是以 Lottie 开头,我们这里就点到为止。后面会在代码实例中介绍更多的 Lottie 属性方法。
我们将从 AE 导出的 json 文件,放置到项目的 assets 文件夹
然后在代码中直接这样引用。
目前引用的场景是在 App 中底部 tab 的正反选
我们再来思考另外一个问题,我们的 APP 有很高的多样化的需求。根据不同的活动要下发不同的样式,底部 tab 也是如此。上面实践的例子是通过加载本地如果我们要动态下发该如何做呢?
通过查询 LottieAnimationView API 我们发现这样一个方法
/**
* Load a lottie animation from a url. The url can be a json file or a zip file. Use a zip file if you have images. Simply zip them together and
* lottie
* will unzip and link the images automatically.
* <p>
* Under the hood, Lottie uses Java HttpURLConnection because it doesn't require any transitive networking dependencies. It will download the file
* to the application cache under a temporary name. If the file successfully parses to a composition, it will rename the temporary file to one that
* can be accessed immediately for subsequent requests. If the file does not parse to a composition, the temporary file will be deleted.
* <p>
* You can replace the default network stack or cache handling with a global {@link LottieConfig}
*
* @see LottieConfig.Builder
* @see Lottie#initialize(LottieConfig)
*/
public void setAnimationFromUrl(String url) {
LottieTask<LottieComposition> task = cacheComposition ?
LottieCompositionFactory.fromUrl(getContext(), url) : LottieCompositionFactory.fromUrl(getContext(), url, null);
setCompositionTask(task);
}
把刚刚本地的 json 文件传到服务(此处感谢文科同学) https://ajiuxian.cn/data.json
代码中进行加载:
结果和本地加载一直,正常网络状态下也没有感觉比本地加载慢。弱网状态下还未做测试。
好了我们解决了动态下发的问题,我们来看看 Lottie 还有哪些局限性。
Lottie 并不是支持所有从 AE 导出的特效,官网有说明,见下图示例
这个没有办法直接通过文字描述知道是否支持,我们实际弄了一些效果测试。试错
我们测试了 6 ~ 7 种特效,都不是支持得特别好见下图(图片来自设计部李晟)
所以实际应用中什么时候用 Lottie 用 gif apng 原生动画我们需要看场景。