标签(空格分隔): json lottie
LottieCompostion
composition : 构成
原文注释:
/**
* After Effects/Bodymovin composition model. This is the serialized model from which the
* animation will be created.
* It can be used with a {@link com.airbnb.lottie.LottieAnimationView} or
* {@link com.airbnb.lottie.LottieDrawable}.
*/
这段意思大致是讲:
利用AE或者Bodymovin会构成一个模型,这段序列化的模型将被用于创建动画。它可以与LottieDrawable,LottieAnimationView一起使用
Lottie的三大核心类,在这段注释上全都涉及到了,从语义上也能看出,这个类的核心功能是获得构建动画的数据,也就是用这个类完成对json解析数据的封装
构造方法
首先json数据有多处来源,可能是你工程自带asset文件中的资源,也可能来源于网络,还有同步与异步的解析方法,因此在构造时为了区分不同的来源,此处采用静态工厂设计模式应对不同的数据源。
- 私有构造方法
内部静态工厂类
public static class Factory {
private Factory() {
}
同步解析
/**
* 从asset中解析
*/
static LottieComposition fromFileSync(Context context, String fileName) {
InputStream stream;
try {
stream = context.getAssets().open(fileName);
} catch (IOException e) {
throw new IllegalStateException("Unable to find file " + fileName, e);
}
return fromInputStream(context.getResources(), stream);
}
/**
* json解析
*/
static LottieComposition fromJsonSync(Resources res, JSONObject json) {
Rect bounds = null;
float scale = res.getDisplayMetrics().density;
int width = json.optInt("w", -1);
int height = json.optInt("h", -1);
if (width != -1 && height != -1) {
int scaledWidth = (int) (width * scale);
int scaledHeight = (int) (height * scale);
bounds = new Rect(0, 0, scaledWidth, scaledHeight);
}
long startFrame = json.optLong("ip", 0);
long endFrame = json.optLong("op", 0);
int frameRate = json.optInt("fr", 0);
LottieComposition composition =
new LottieComposition(bounds, startFrame, endFrame, frameRate, scale);
JSONArray assetsJson = json.optJSONArray("assets");
parseImages(assetsJson, composition);
parsePrecomps(assetsJson, composition);
parseLayers(json, composition);
return composition;
}
异步解析
两个继承了AsyncTask的异步解析类,一个用来解析文件,一个用来解析json
- JsonCompositionLoader ->CompositionLoader -> AsyncTask
- FileCompositionLoader ->CompositionLoader -> AsyncTask
解析方式差不多,只不过更换成为了异步,实现了一个Cancellable接口,用于取消解析