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

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

使用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

1.8k
OkHttp线程池和连接池
开源

OkHttp线程池和连接池

OkHttp线程池和连接池了解了OkHttp的网络请求流程以及拦截器实现原理,再关注OkHttp中两个重要的:OkHttp的线程池和连接池。1、OkHttp线程池在OkHttp网络请求流程一文中,我们分析了OkHttp异步和同步请求流程。请求最后都在Dispatcher中分发调度处理,最后被ExecutorService执行。1.1、DispatcherDispatcher中执行任务的执行器是ex

5.2k
优美的开源动效库:Lottie
开源

优美的开源动效库:Lottie

优美的开源动效库:Lottie1、强大的动效LottieLottie是一个适用于Android,iOS,Web和Windows的库,它可以使用Bodymovin解析以json格式导出的Adobe After Effects动画,并在移动设备和Web上原生渲染它们!GitHub:https://github.com/airbnb/lottie-androidLottie官网:http://airbn

4.3k