使用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文件会大几倍。