音视频开发之旅(62) -Lottie 源码分析之json解析

2024-06-12 06:18

本文主要是介绍音视频开发之旅(62) -Lottie 源码分析之json解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  1. Lottie能做什么
  2. Lottie 动画使用调用流程
  3. Json字段介绍
  4. 解析为LottieComposition
  5. 资料
  6. 总结

一、Lottie能做什么

在实现动画方面,原生的方式开发成本比较高,airbnb开源的lottie有Android、iOS、RN等多个版本的支持,设计师通过AE设计好动画后,通过AE插件Bodymovin导出json和素材文件。

可以上 https://lottiefiles.com/popular 看看一些流行的 Lottie 动效

客户端通过加载解析渲染播放 即可实现对应的动画效果,这个思路和设计非常值得学习借鉴。接下来两篇我们对其进行学习分析,欢迎讨论交流。

二、Lottie 动画使用调用流程

Lottie 的动画调用流程

1. 创建LottieAnimationView
2. 创建LottieDrawable
3. 解析json文件为LottieComposition对象
4. lottieDrawable.setComposition(lottieComposition)lottieAnimationView.setImageDrawable(lottieDrawable)
5. 播放动画playAnimation()
在onValueChanged时,各个创建好的Drawable会根据需求进行重绘,达到动画的效果。

对于开发者使用非常简单, 可以参考lottie源码中sample的使用。

三、Json字段介绍

我们以Lottie-android提供的demo中的AndroidWave.json和anima.json 为例来学习
object

下面我们看下assets中的字段
object->assets:资源

可以看到object中有layers ,assets中也可能有layers,那边layers这个图层字段包含了什么信息呐。
object->layers:图层

object->layers->ty:图层类型

object->layers->ks:图层变换

“o 、r、 p、 a、 s”中字段相同,都是a、k、x、ix 下面对a、k做说明。x、ix也不知道什么用处。
object->layers->ks-> o 、r、 p、 a、 s

Lottie json的字段基本解释完,下面我们结合Lottie-android的源码看下解析为LottieComposition的过程

四、 解析为LottieComposition

json的解析器,解析为LottieComposition对象

 

4.1 LottieComposition解析的过程

LottieComposition对象

json的解析器,解析为LottieComposition对象

//lottie json的解析器,解析为LottieComposition对象
public class LottieCompositionMoshiParser {private static final JsonReader.Options NAMES = JsonReader.Options.of("w", // 0"h", // 1"ip", // 2"op", // 3"fr", // 4"v", // 5"layers", // 6"assets", // 7"fonts", // 8"chars", // 9"markers" // 10);public static LottieComposition parse(JsonReader reader) throws IOException {float scale = Utils.dpScale();float startFrame = 0f;float endFrame = 0f;float frameRate = 0f;final LongSparseArray<Layer> layerMap = new LongSparseArray<>();final List<Layer> layers = new ArrayList<>();int width = 0;int height = 0;Map<String, List<Layer>> precomps = new HashMap<>();Map<String, LottieImageAsset> images = new HashMap<>();Map<String, Font> fonts = new HashMap<>();List<Marker> markers = new ArrayList<>();SparseArrayCompat<FontCharacter> characters = new SparseArrayCompat<>();LottieComposition composition = new LottieComposition();reader.beginObject();while (reader.hasNext()) {switch (reader.selectName(NAMES)) {case 0:width = reader.nextInt();break;case 1:height = reader.nextInt();break;case 2:startFrame = (float) reader.nextDouble();break;case 3:endFrame = (float) reader.nextDouble() - 0.01f;break;case 4:frameRate = (float) reader.nextDouble();break;case 5:String version = reader.nextString();String[] versions = version.split("\\.");int majorVersion = Integer.parseInt(versions[0]);int minorVersion = Integer.parseInt(versions[1]);int patchVersion = Integer.parseInt(versions[2]);if (!Utils.isAtLeastVersion(majorVersion, minorVersion, patchVersion,4, 4, 0)) {composition.addWarning("Lottie only supports bodymovin >= 4.4.0");}break;case 6://重点看下parseLayers的实现parseLayers(reader, composition, layers, layerMap);break;case 7:parseAssets(reader, composition, precomps, images);break;case 8:parseFonts(reader, fonts);break;case 9:parseChars(reader, composition, characters);break;case 10:parseMarkers(reader, markers);break;default:reader.skipName();reader.skipValue();}}// w、h会根据像素密度自动适配int scaledWidth = (int) (width * scale);int scaledHeight = (int) (height * scale);Rect bounds = new Rect(0, 0, scaledWidth, scaledHeight);//json内容解析完之后,调用composition的init进行LottieComposition字段的赋值,完成json对LottieComposition的工作composition.init(bounds, startFrame, endFrame, frameRate, layers, layerMap, precomps,images, characters, fonts, markers);return composition;}private static void parseLayers(JsonReader reader, LottieComposition composition,List<Layer> layers, LongSparseArray<Layer> layerMap) throws IOException {int imageCount = 0;reader.beginArray();//遍历解析每个layer图层,while (reader.hasNext()) {//图层解析Layer layer = LayerParser.parse(reader, composition);if (layer.getLayerType() == Layer.LayerType.IMAGE) {imageCount++;}//加入到layers和map提高效率layers.add(layer);layerMap.put(layer.getId(), layer);}reader.endArray();}

4.2 layers图层的解析过程

被解析为Layer对象

通过LayerParser把json中layers解析为Layer对象

//通过LayerParser把json中layers解析为Layer对象
public class LayerParser {//对应 json中layers的字段private static final JsonReader.Options NAMES = JsonReader.Options.of("nm", // 0"ind", // 1"refId", // 2"ty", // 3"parent", // 4"sw", // 5"sh", // 6"sc", // 7"ks", // 8"tt", // 9"masksProperties", // 10"shapes", // 11"t", // 12"ef", // 13"sr", // 14"st", // 15"w", // 16"h", // 17"ip", // 18"op", // 19"tm", // 20"cl", // 21"hd" // 22);private static final JsonReader.Options TEXT_NAMES = JsonReader.Options.of("d","a");private static final JsonReader.Options EFFECTS_NAMES = JsonReader.Options.of("ty","nm");public static Layer parse(JsonReader reader, LottieComposition composition) throws IOException {// This should always be set by After Effects. However, if somebody wants to minify// and optimize their json, the name isn't critical for most cases so it can be removed.String layerName = "UNSET";Layer.LayerType layerType = null;String refId = null;long layerId = 0;int solidWidth = 0;int solidHeight = 0;int solidColor = 0;int preCompWidth = 0;int preCompHeight = 0;long parentId = -1;float timeStretch = 1f;float startFrame = 0f;float inFrame = 0f;float outFrame = 0f;String cl = null;boolean hidden = false;BlurEffect blurEffect = null;DropShadowEffect dropShadowEffect = null;Layer.MatteType matteType = Layer.MatteType.NONE;AnimatableTransform transform = null;AnimatableTextFrame text = null;AnimatableTextProperties textProperties = null;AnimatableFloatValue timeRemapping = null;List<Mask> masks = new ArrayList<>();List<ContentModel> shapes = new ArrayList<>();reader.beginObject();while (reader.hasNext()) {switch (reader.selectName(NAMES)) {case 0:layerName = reader.nextString();break;case 1:layerId = reader.nextInt();break;case 2:refId = reader.nextString();break;case 3:int layerTypeInt = reader.nextInt();//看下Layer.LayerType的值 对应json中tyif (layerTypeInt < Layer.LayerType.UNKNOWN.ordinal()) {layerType = Layer.LayerType.values()[layerTypeInt];} else {layerType = Layer.LayerType.UNKNOWN;}break;case 4:parentId = reader.nextInt();break;case 5:solidWidth = (int) (reader.nextInt() * Utils.dpScale());break;case 6:solidHeight = (int) (reader.nextInt() * Utils.dpScale());break;case 7:solidColor = Color.parseColor(reader.nextString());break;case 8://图层变换,动画的 这个重点看下 transform = AnimatableTransformParser.parse(reader, composition);break;case 9:int matteTypeIndex = reader.nextInt();if (matteTypeIndex >= Layer.MatteType.values().length) {composition.addWarning("Unsupported matte type: " + matteTypeIndex);break;}matteType = Layer.MatteType.values()[matteTypeIndex];switch (matteType) {case LUMA:composition.addWarning("Unsupported matte type: Luma");break;case LUMA_INVERTED:composition.addWarning("Unsupported matte type: Luma Inverted");break;}composition.incrementMatteOrMaskCount(1);break;case 10://蒙层解析reader.beginArray();while (reader.hasNext()) {masks.add(MaskParser.parse(reader, composition));}composition.incrementMatteOrMaskCount(masks.size());reader.endArray();break;case 11:reader.beginArray();while (reader.hasNext()) {ContentModel shape = ContentModelParser.parse(reader, composition);if (shape != null) {shapes.add(shape);}}reader.endArray();break;case 12:reader.beginObject();while (reader.hasNext()) {switch (reader.selectName(TEXT_NAMES)) {case 0:text = AnimatableValueParser.parseDocumentData(reader, composition);break;case 1:reader.beginArray();if (reader.hasNext()) {textProperties = AnimatableTextPropertiesParser.parse(reader, composition);}while (reader.hasNext()) {reader.skipValue();}reader.endArray();break;default:reader.skipName();reader.skipValue();}}reader.endObject();break;case 13://特效reader.beginArray();List<String> effectNames = new ArrayList<>();while (reader.hasNext()) {reader.beginObject();while (reader.hasNext()) {switch (reader.selectName(EFFECTS_NAMES)) {case 0:int type = reader.nextInt();if (type == 29) {blurEffect = BlurEffectParser.parse(reader, composition);} else if (type == 25) {dropShadowEffect = new DropShadowEffectParser().parse(reader, composition);}break;case 1:String effectName = reader.nextString();effectNames.add(effectName);break;default:reader.skipName();reader.skipValue();}}reader.endObject();}reader.endArray();composition.addWarning("Lottie doesn't support layer effects. If you are using them for " +" fills, strokes, trim paths etc. then try adding them directly as contents " +" in your shape. Found: " + effectNames);break;case 14:timeStretch = (float) reader.nextDouble();break;case 15:startFrame = (float) reader.nextDouble();break;case 16:preCompWidth = (int) (reader.nextInt() * Utils.dpScale());break;case 17:preCompHeight = (int) (reader.nextInt() * Utils.dpScale());break;case 18:inFrame = (float) reader.nextDouble();break;case 19:outFrame = (float) reader.nextDouble();break;case 20:timeRemapping = AnimatableValueParser.parseFloat(reader, composition, false);break;case 21:cl = reader.nextString();break;case 22:hidden = reader.nextBoolean();break;default:reader.skipName();reader.skipValue();}}reader.endObject();List<Keyframe<Float>> inOutKeyframes = new ArrayList<>();// Before the in frameif (inFrame > 0) {Keyframe<Float> preKeyframe = new Keyframe<>(composition, 0f, 0f, null, 0f, inFrame);inOutKeyframes.add(preKeyframe);}// The + 1 is because the animation should be visible on the out frame itself.outFrame = (outFrame > 0 ? outFrame : composition.getEndFrame());Keyframe<Float> visibleKeyframe =new Keyframe<>(composition, 1f, 1f, null, inFrame, outFrame);inOutKeyframes.add(visibleKeyframe);Keyframe<Float> outKeyframe = new Keyframe<>(composition, 0f, 0f, null, outFrame, Float.MAX_VALUE);inOutKeyframes.add(outKeyframe);if (layerName.endsWith(".ai") || "ai".equals(cl)) {composition.addWarning("Convert your Illustrator layers to shape layers.");}//根据上面解析的值,生成对应的Layer对象。这个对象是进行绘制return new Layer(shapes, composition, layerName, layerId, layerType, parentId, refId,masks, transform, solidWidth, solidHeight, solidColor, timeStretch, startFrame,preCompWidth, preCompHeight, text, textProperties, inOutKeyframes, matteType,timeRemapping, hidden, blurEffect, dropShadowEffect);}
}

4.3 ks图层变换的解析过程

被解析为对象AnimatableTransform

通过AnimatableTransformParser把json中ks解析为AnimatableTransform对象

//通过AnimatableTransformParser把json中ks解析为AnimatableTransform对象
public class AnimatableTransformParser {private static final JsonReader.Options NAMES = JsonReader.Options.of("a",  // 1"p",  // 2"s",  // 3"rz", // 4"r",  // 5"o",  // 6"so", // 7"eo", // 8"sk", // 9"sa"  // 10);private static final JsonReader.Options ANIMATABLE_NAMES = JsonReader.Options.of("k");public static AnimatableTransform parse(JsonReader reader, LottieComposition composition) throws IOException {AnimatablePathValue anchorPoint = null;AnimatableValue<PointF, PointF> position = null;AnimatableScaleValue scale = null;AnimatableFloatValue rotation = null;AnimatableIntegerValue opacity = null;AnimatableFloatValue startOpacity = null;AnimatableFloatValue endOpacity = null;AnimatableFloatValue skew = null;AnimatableFloatValue skewAngle = null;boolean isObject = reader.peek() == JsonReader.Token.BEGIN_OBJECT;if (isObject) {reader.beginObject();}while (reader.hasNext()) {switch (reader.selectName(NAMES)) {case 0: // areader.beginObject();while (reader.hasNext()) {switch (reader.selectName(ANIMATABLE_NAMES)) {case 0:anchorPoint = AnimatablePathValueParser.parse(reader, composition);break;default:reader.skipName();reader.skipValue();}}reader.endObject();break;case 1: // pposition =AnimatablePathValueParser.parseSplitPath(reader, composition);break;case 2: // sscale = AnimatableValueParser.parseScale(reader, composition);break;case 3: // rzcomposition.addWarning("Lottie doesn't support 3D layers.");case 4: // rrotation = AnimatableValueParser.parseFloat(reader, composition, false);if (rotation.getKeyframes().isEmpty()) {rotation.getKeyframes().add(new Keyframe<>(composition, 0f, 0f, null, 0f, composition.getEndFrame()));} else if (rotation.getKeyframes().get(0).startValue == null) {rotation.getKeyframes().set(0, new Keyframe<>(composition, 0f, 0f, null, 0f, composition.getEndFrame()));}break;case 5: // oopacity = AnimatableValueParser.parseInteger(reader, composition);break;case 6: // sostartOpacity = AnimatableValueParser.parseFloat(reader, composition, false);break;case 7: // eoendOpacity = AnimatableValueParser.parseFloat(reader, composition, false);break;case 8: // skskew = AnimatableValueParser.parseFloat(reader, composition, false);break;case 9: // saskewAngle = AnimatableValueParser.parseFloat(reader, composition, false);break;default:reader.skipName();reader.skipValue();}}if (isObject) {reader.endObject();}if (isAnchorPointIdentity(anchorPoint)) {anchorPoint = null;}if (isPositionIdentity(position)) {position = null;}if (isRotationIdentity(rotation)) {rotation = null;}if (isScaleIdentity(scale)) {scale = null;}if (isSkewIdentity(skew)) {skew = null;}if (isSkewAngleIdentity(skewAngle)) {skewAngle = null;}//根据解析的属性生成AnimatableTransform对象return new AnimatableTransform(anchorPoint, position, scale, rotation, opacity, startOpacity, endOpacity, skew, skewAngle);}

五、资料

  1. Lottie 的使用
  2. Lottie实现思路和源码分析
  3. 如何看懂json参数
  4. Lottie—json文件解析
  5. Lottie 还可以做这些?

六、收获

通过本篇的学习

  1. 了解Lottie动画的流程
  2. 了解lottie json的中每个字段的含义
  3. 分析lottie json解析过程

感谢你的阅读
下一篇我们分析学习Layer渲染和动画部分的实现,欢迎关注公众号“音视频开发之旅”,一起学习成长。
欢迎交流

这篇关于音视频开发之旅(62) -Lottie 源码分析之json解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1053411

相关文章

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

SpringBoot 多环境开发实战(从配置、管理与控制)

《SpringBoot多环境开发实战(从配置、管理与控制)》本文详解SpringBoot多环境配置,涵盖单文件YAML、多文件模式、MavenProfile分组及激活策略,通过优先级控制灵活切换环境... 目录一、多环境开发基础(单文件 YAML 版)(一)配置原理与优势(二)实操示例二、多环境开发多文件版

使用docker搭建嵌入式Linux开发环境

《使用docker搭建嵌入式Linux开发环境》本文主要介绍了使用docker搭建嵌入式Linux开发环境,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录1、前言2、安装docker3、编写容器管理脚本4、创建容器1、前言在日常开发全志、rk等不同

深度解析Python中递归下降解析器的原理与实现

《深度解析Python中递归下降解析器的原理与实现》在编译器设计、配置文件处理和数据转换领域,递归下降解析器是最常用且最直观的解析技术,本文将详细介绍递归下降解析器的原理与实现,感兴趣的小伙伴可以跟随... 目录引言:解析器的核心价值一、递归下降解析器基础1.1 核心概念解析1.2 基本架构二、简单算术表达

MyBatis-plus处理存储json数据过程

《MyBatis-plus处理存储json数据过程》文章介绍MyBatis-Plus3.4.21处理对象与集合的差异:对象可用内置Handler配合autoResultMap,集合需自定义处理器继承F... 目录1、如果是对象2、如果需要转换的是List集合总结对象和集合分两种情况处理,目前我用的MP的版本

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

C#下Newtonsoft.Json的具体使用

《C#下Newtonsoft.Json的具体使用》Newtonsoft.Json是一个非常流行的C#JSON序列化和反序列化库,它可以方便地将C#对象转换为JSON格式,或者将JSON数据解析为C#对... 目录安装 Newtonsoft.json基本用法1. 序列化 C# 对象为 JSON2. 反序列化

Python中Json和其他类型相互转换的实现示例

《Python中Json和其他类型相互转换的实现示例》本文介绍了在Python中使用json模块实现json数据与dict、object之间的高效转换,包括loads(),load(),dumps()... 项目中经常会用到json格式转为object对象、dict字典格式等。在此做个记录,方便后续用到该方

Java MCP 的鉴权深度解析

《JavaMCP的鉴权深度解析》文章介绍JavaMCP鉴权的实现方式,指出客户端可通过queryString、header或env传递鉴权信息,服务器端支持工具单独鉴权、过滤器集中鉴权及启动时鉴权... 目录一、MCP Client 侧(负责传递,比较简单)(1)常见的 mcpServers json 配置