使用Lottie报错:You must set an images folder before loading an image

QuibblerQuibbler 2025-09-29 约 5 分钟 1244 次阅读

使用Lottie报错:You must set an images folder before loading an image

上一篇关于Lottie的博客还是5年前写的:优美的开源动效库:Lottie。Lottie依旧是复杂动画最优雅的实现,工作量交给设计师, 开发只需要拿着设计师提供的JSON动效文件加载即可。

很久没有使用Lottie,拿到JSON格式文件,按照之前的方式直接加载,使用Lottie的时候竟然报这个错:You must set an images folder before loading an image. 

原来是设计师在动画中额外使用了几张图片:

{"v":"5.11.0","fr":60,"ip":0,"op":181,"w":1740,"h":1740,"nm":"color flow name","ddd":0,"assets":[{"id":"image_0","w":492,"h":492,"u":"images/","p":"img_0.png","e":0},{"id":"image_1","w":322,"h":322,"u":"images/","p":"img_1.png","e":0}}

这些图片作为动效的一部分,也需要放到项目中。原因是当开始动画的时候,LottieDrawable通过getBitmapForId(String id)方法获取图片Bitmap资源:

@Nullable
    public Bitmap getBitmapForId(String id) {
      ImageAssetManager assetManager = getImageAssetManager();
      if (assetManager != null) {
        return assetManager.bitmapForId(id);
      }
      return null;
    }

进一步通过id从ImageAssetManager读取对应名称的图片资源,发现没有设置资源目录imagesFolder,就会抛出异常。

@Nullable public Bitmap bitmapForId(String id) {
      LottieImageAsset asset = imageAssets.get(id);
      ...
      InputStream is;
      try {
        if (TextUtils.isEmpty(imagesFolder)) {
          throw new IllegalStateException("You must set an images folder before loading an image." +
              " Set it with LottieComposition#setImagesFolder or LottieDrawable#setImagesFolder");
        }
        is = context.getAssets().open(imagesFolder + filename);
      } catch (IOException e) {
        Logger.warning("Unable to open asset.", e);
        return null;
      }
      ...
      return putBitmap(id, bitmap);
    }

解决办法很简单:

①在assets下面新建一个文件夹images,将设计师提供的png图片资源放到里面。

②把images资源的路径通过setImageAssetsFolder()方法设置给LottieAnimationView

animation.setImageAssetsFolder("images/")

③也可以在xml里设置该目录:

<com.airbnb.lottie.LottieAnimationView
	android:id="@+id/lottie_anim"
	app:lottie_fileName="loading_yoyo.json"
	app:lottie_imageAssetsFolder="images"/>

设置目录很关键。只要目录设置了,就算资源文件缺失也不会报错,只是动画不执行或者显示异常。

当然也可以让设计师将其整合到一个完整的JSON动效文件中,这样只需要加载一个,缺点是JSON文件会大几倍。

相关推荐

Airbnb开源项目
精选开源

Airbnb开源项目

Airbnb Engineering & Data ScienceAirflow Use Apache Airflow (incubating) to author workflows as directed acyclic graphs (DAGs) of tasks12,263Airpal Web UI for PrestoDB2,502Aerosolve A machine learning

2.3k
WilliamChart:轻量美观的 Android 图表库实战
精选开源

WilliamChart:轻量美观的 Android 图表库实战

WilliamChart:轻量美观的 Android 图表库实战数据可视化是运动、健康、金融、统计类 App 的刚需。MPAndroidChart 功能最全但偏重复杂,WilliamChart 走的则是"轻量 + 美观 + Kotlin 原生"路线——v3 用 Kotlin 完全重写,API 极简,一行 chart.animate(dataSet) 就能把数据画成带动画的折线/柱状/环形图,开箱即

175
sherpa解析:开源语音技术全家桶
精选开源

sherpa解析:开源语音技术全家桶

想在手机、树莓派甚至 RISC-V 开发板上离线跑语音识别,五年前还是个需要啃 Kaldi 源码的硬核课题。k2-fsa 组织的 sherpa 把这件事变成了"下载预训练模型、装个包、跑示例"的三步操作。这个以 Apache-2.0 协议开源的项目自我定位是"新一代 Kaldi 的语音转文本框架",它专注端到端模型的推理部署:transducer 与 CTC 两类架构,C++ 与 Python 双…

44