lottie-turbo 源码解读(一):lottie_bridge 与 Animator------声明式配置到 native 渲染的桥接
先看声明式配置有多简单
用 lottie-turbo 播一个 Lottie 动画,你只需要:
💡 LottieView 声明式配置示例(非库源码原文)
typescript
LottieView({
lottieId: 'lottie1',
resource: $rawfile('anim.json'),
loop: true,
autoplay: true,
controller: this.controller,
})
一行声明,动画就动了。 但问题是:LottieView 只是个声明式组件,它自己并不会画图------那动画的每一帧是谁、在什么线程、用什么 API 画到屏幕上的?
答案在 lottie_bridge 的三层桥接:LottieContext 持有 LottieHandler 和 LottieXcomponentNode,LottieXcomponentNode 负责 XComponent 节点与布局渲染,Animator 负责动画状态机与帧驱动。
本文内容 :拆解声明式配置到 native 渲染的完整链路------LottieContext 怎么桥接前后台、LottieXcomponentNode 怎么创建 XComponent 节点并处理布局与渲染、Animator 怎么用状态机驱动帧播放、ShouldSkipFrame 怎么在不可见时跳过绘制、以及 DisposeHandleOnUIThread 为什么必须在 UI 线程释放。读完你会确切知道:声明式的一行配置,是怎么变成 native 侧一帧一帧的渲染调用的。
📦 仓库地址 | 本文基于 v1.0.14-rc.2 源码根目录:
library/src/main/cpp/,下文路径均相对于此。
一、先建立图景:前台与后厨
把 lottie-turbo 的渲染想象成前台与后厨:
LottieView是前台:你告诉它"播哪个动画、循环不循环、自动播不播",它把配置记下来。LottieContext是传菜口 :它持有LottieHandler(动画数据与逻辑)和LottieXcomponentNode(渲染节点),把前台的配置传给后厨。LottieXcomponentNode是后厨的灶台 :用OH_NativeXComponent创建渲染节点,负责布局(cover/adaptive 等)和实际绘制。Animator是后厨的火候 :用ArkUI_AnimatorHandle驱动动画状态机(IDLE/PLAY/PAUSE/STOP/END),按帧率推进渲染。
核心结论先说清楚:LottieView 只是声明式配置,真正的渲染由 LottieXcomponentNode(节点与绘制)和 Animator(帧驱动与状态机)在 native 侧完成。
二、LottieContext:前后台的桥接点
LottieContext 在 lottie_bridge.h,是前台配置和后厨渲染之间的桥接点:
📄 lottie_bridge.h
cpp
class LottieContext {
public:
LottieContext(napi_value contentView, CLottieConfig *lottieConfig);
std::shared_ptr<LottieHandler> GetLottieHandle();
std::shared_ptr<LottieXcomponentNode> GetXcomponentNode();
ArkUI_NodeContentHandle GetNodeContentHandle();
~LottieContext();
private:
std::shared_ptr<LottieHandler> lottieHandle_{nullptr};
std::shared_ptr<LottieXcomponentNode> lottieNode_{nullptr};
napi_ref ref_;
};
它持有两个核心对象:
lottieHandle_:LottieHandler,动画的数据与逻辑处理器(JSON 解析、动画模型、帧数据)。lottieNode_:LottieXcomponentNode,XComponent 渲染节点(真正画图的地方)。
GetNodeContentHandle() 返回 ArkUI_NodeContentHandle------这就是 ArkTS 侧 ContentSlot 需要的挂载点 。前台 LottieView 通过这个句柄把后厨的渲染节点挂到自己的布局里。
ref_ 是 napi_ref,用于保持 JS 侧对象的引用,防止被 GC 回收------这是前后台对象生命周期的桥接点。
所以 LottieContext 的角色就是"传菜口" :前台声明式配置(LottieView)通过它拿到后厨的渲染节点和动画处理器,后厨则通过它把渲染结果送回前台的挂载点。
三、LottieXcomponentNode:XComponent 节点与渲染
LottieXcomponentNode 是真正"做菜"的地方。它在 node/lottie_xcomponent_node.h,封装了 OH_NativeXComponent。
📄 node/lottie_xcomponent_node.h
cpp
class LottieXcomponentNode {
public:
LottieXcomponentNode(std::string xcomponentId, float radius, double bgColor, std::string renderMode = "");
~LottieXcomponentNode();
ArkUI_NodeHandle GetHandle() const;
/**
* @brief 创建Xcomponent组件并节点上树
* @param xcomponentId 组件Id
* @param radius 边框圆角
* @param bgColor 背景颜色
* @param renderMode 渲染模式,支持 'texture'(API18+),默认为 surface 模式
*/
void CreateXcomponentNode(std::string xcomponentId, float radius, double bgColor, std::string renderMode = "");
/**
* 初始化回调函数并渲染第一帧
*/
void Init();
/**
* 调度渲染任务到线程池
* @param absoluteFrameToPlay 要渲染的绝对帧
* @param current 当前索引
*/
void ScheduleRenderTask(float absoluteFrameToPlay, int64_t current);
/**
* 渲染当前帧(仅绘制)
*/
void RenderCurrentFrame();
/**
* 渲染当前帧并推进到下一个待绘制帧
*/
void RenderAndAdvanceFrame();
/**
* 设置定时器
*/
void SetAnimator();
/**
* 绑定LottieHandler
*/
void SetHandler(std::shared_ptr<LottieHandler> LottieHandler);
/**
* 在UI线程上释放原生节点句柄,必须在DisposeLottieNode流程中调用
*/
void DisposeHandleOnUIThread();
private:
static void OnSurfaceCreated(OH_NativeXComponent *component, void *window);
static void OnSurfaceChanged(OH_NativeXComponent *component, void *window);
static void OnSurfaceDestroyed(OH_NativeXComponent *component, void *window);
/**
* 检查是否应该跳过当前帧
* @param handler LottieHandler指针
* @param current 当前帧索引
* @return true表示应该跳帧,false表示需要渲染
*/
bool ShouldSkipFrame(std::shared_ptr<LottieHandler> handler, int64_t current);
/**
* 生成渲染树
* @param handler LottieHandler指针
* @param position 位置信息
* @param render 渲染器
* @param absoluteFrameToPlay 要渲染的绝对帧
* @return 渲染树节点指针
*/
const LOTLayerNode *GenerateRenderTree(std::shared_ptr<LottieHandler> handler, const CalculatePosition &position,
std::shared_ptr<LottieRender> render, float absoluteFrameToPlay);
OH_NativeXComponent *nativeXComponent_{nullptr};
ArkUI_NativeNodeAPI_1 *arkUINativeNodeApi_{nullptr};
ArkUI_NodeHandle handle_;
std::shared_ptr<LottieHandler> lottieHandler_{nullptr};
std::shared_ptr<LottieRender> lottieRender_{nullptr};
std::string contentMode_;
CalculatePosition position_;
std::atomic<int8_t> status_{0};
std::atomic<bool> disposed_{false};
bool firstFrame_{true};
bool firstRender_{true};
};
它做了六件事:
① 创建 XComponent 节点 :CreateXcomponentNode(xcomponentId, radius, bgColor, renderMode) 创建并上树,renderMode 支持 'texture'(API 18+ 硬件加速)和默认的 surface 模式。
② 初始化并渲染第一帧 :Init() 初始化回调并渲染第一帧,firstFrame_ 和 firstRender_ 标记首帧状态。
③ 调度渲染任务 :ScheduleRenderTask(absoluteFrameToPlay, current) 把渲染任务派到线程池,不在主线程做重活。
④ 帧渲染与推进 :RenderCurrentFrame() 只画当前帧,RenderAndAdvanceFrame() 画完并推进到下一帧。
⑤ 布局处理 :InitializePosition、ApplyCoverMode、ApplyAdaptiveWidthMode、ApplyAdaptiveHeightMode 等,处理 cover / top/bottom / containCrop / adaptiveWidth / adaptiveHeight 各种布局模式。
⑥ 生命周期管理 :OnSurfaceCreated / OnSurfaceChanged / OnSurfaceDestroyed 三个静态回调处理 surface 的创建、变化、销毁;DisposeHandleOnUIThread() 在 UI 线程释放节点句柄。
SetHandler 绑定 LottieHandler,让节点知道要渲染哪个动画数据。
GenerateRenderTree 则根据 handler、position、render、目标帧生成渲染树节点------这是"数据 → 渲染指令"的关键一步。
四、Animator:动画状态机与帧驱动
Animator 在 animator/animator.h,负责动画的状态机与帧率控制。
📄 animator/animator.h
cpp
class Animator {
public:
enum class AnimatorStatus {
IDLE, INIT, PLAY, STOP, END, PAUSE
};
~Animator();
int32_t SetDuration(int32_t duration);
int32_t SetDelay(int32_t delay);
int32_t SetIterations(int32_t);
int32_t SetBegin(float begin);
int32_t SetEnd(float end);
int32_t SetEasing(ArkUI_AnimationCurve easing);
int32_t SetDirection(ArkUI_AnimationDirection direction);
int32_t SetFill(ArkUI_AnimationFillMode fill);
void SetFrameRateRange(ArkUI_ExpectedFrameRateRange frameRateRange);
ArkUI_ExpectedFrameRateRange GetSetFrameRateRange() const;
int32_t UpdateFrameRateRange();
void Init(ArkUI_ContextHandle context);
std::function<void()> FunctionCallBack;
int32_t Play();
int32_t Pause();
int32_t Stop();
const AnimatorStatus GetStatus() const;
void SetSafeFunc(napi_threadsafe_function safeFunc);
private:
int32_t duration_{0};
ArkUI_AnimationCurve easing_{ARKUI_CURVE_LINEAR};
int32_t delay_{0};
ArkUI_AnimationDirection direction_{ARKUI_ANIMATION_DIRECTION_NORMAL};
int32_t iterations_{-1};
float begin_{0};
float end_{1};
ArkUI_ExpectedFrameRateRange frameRateRange_{.min = 0, .max = 0, .expected = 0};
ArkUI_AnimationFillMode fill_{ARKUI_ANIMATION_FILL_MODE_FORWARDS};
ArkUI_AnimatorOption *animatorOption_{nullptr};
ArkUI_AnimatorHandle animatorHandle_{nullptr};
ArkUI_NativeAnimateAPI_1 *animateAPi_1_{nullptr};
static void OnCallBack(ArkUI_AnimatorOnFrameEvent *event);
std::atomic<AnimatorStatus> status_{Animator::AnimatorStatus::IDLE};
napi_threadsafe_function safeFunc_{nullptr};
};
状态机是 IDLE / INIT / PLAY / STOP / END / PAUSE 六种状态 ,用 std::atomic<AnimatorStatus> status_ 保证线程安全------因为状态可能在不同线程被读写。
ArkUI_AnimatorHandle 是 ArkUI 的动画器句柄,驱动动画按帧率推进。OnCallBack 是静态帧事件回调,每次动画帧更新时触发。
SetDuration / SetDelay / SetIterations / SetBegin / SetEnd / SetEasing / SetDirection / SetFill 对应你声明式配置里的参数:播放时长、延迟、循环次数、起止进度、缓动曲线、播放方向、填充模式。
SetFrameRateRange 和 UpdateFrameRateRange 设置期望帧率范围,UpdateFrameRateRange 把它同步给 ArkUI------这就是控制动画流畅度的入口。
SetSafeFunc(napi_threadsafe_function) 是跨线程回调函数,用于在子线程完成渲染后安全地通知 JS 侧------和 TaskRunner 的 threadsafe function 是同一套机制。
五、ShouldSkipFrame:不可见时自动跳过绘制
LottieXcomponentNode 里有个 ShouldSkipFrame 方法:
📄 node/lottie_xcomponent_node.h
cpp
/**
* 检查是否应该跳过当前帧
* @param handler LottieHandler指针
* @param current 当前帧索引
* @return true表示应该跳帧,false表示需要渲染
*/
bool ShouldSkipFrame(std::shared_ptr<LottieHandler> handler, int64_t current);
它的作用是:判断当前帧该不该跳过不画。当组件不可见(滑出屏幕、页面切后台)时,继续渲染纯浪费电------所以直接跳过。
这就是 lottie-turbo 文档里说的**"动画不可见时自动跳过绘制,减少功耗"**的实现位置。
为什么这对多动画场景重要? 一屏 20 个 LottieView,如果每个都在后台持续渲染,主线程直接卡死。ShouldSkipFrame 让不可见的动画停止渲染,主线程压力骤减。
它和 LottieController 的 pause() 不同:pause() 是暂停播放但保留当前帧状态 ,ShouldSkipFrame 是直接跳过绘制。前者是用户主动暂停,后者是框架自动省电。
六、DisposeHandleOnUIThread:UI 线程安全释放
DisposeHandleOnUIThread 的注释写着"在UI线程上释放原生节点句柄,必须在DisposeLottieNode流程中调用":
📄 node/lottie_xcomponent_node.h
cpp
/**
* 在UI线程上释放原生节点句柄,必须在DisposeLottieNode流程中调用
*/
void DisposeHandleOnUIThread();
为什么必须在 UI 线程释放? 因为 ArkUI_NodeHandle 和 XComponent 节点都是线程绑定的------它们只能在创建它们的 UI 线程上销毁。如果在子线程销毁,就会触发多线程访问错误。
这就是 Issue #229 / #230(DisposeLottieNode 从 NAPI 异步回调触发概率崩溃)的根因 :DisposeLottieNode 如果从 NAPI 异步回调(非 UI 线程)触发,销毁节点时就会崩。修复方式就是强制在 UI 线程执行 DisposeHandleOnUIThread。
disposed_ 是 std::atomic<bool>,标记是否已释放,防止重复销毁。
这对应了异步释放的正确姿势 :aboutToDisappear 里先 controller.stop() 停掉动画,再让节点在 UI 线程安全销毁------先停再销毁,避免渲染中销毁导致崩溃。
七、回到最初的问题:声明式配置到 native 渲染的完整链路
开头的疑问是"LottieView 一行声明,动画是谁画出来的",现在可以完整回答:
css
你写的 LottieView 配置
↓
LottieContext(桥接点)
├─ LottieHandler ← 动画数据与逻辑(JSON 解析、模型、帧数据)
└─ LottieXcomponentNode ← XComponent 节点与渲染
↓
CreateXcomponentNode 创建节点(surface / texture)
Init 初始化并渲染第一帧
GenerateRenderTree 按 handler + position + 目标帧生成渲染树
ScheduleRenderTask 渲染任务派到线程池
RenderAndAdvanceFrame 画当前帧并推进下一帧
↓
Animator(帧驱动与状态机)
├─ SetFrameRateRange / UpdateFrameRateRange 控制帧率
├─ Play / Pause / Stop 状态机切换(IDLE/PLAY/PAUSE/STOP/END)
└─ OnCallBack(帧事件) 驱动逐帧渲染
↓
ShouldSkipFrame 不可见时跳过绘制(省电)
DisposeHandleOnUIThread UI 线程安全释放(避免 #229/#230 崩溃)
| 环节 | 谁做 | 做什么 |
|---|---|---|
| 桥接 | LottieContext |
持有 handler 和节点,提供 GetNodeContentHandle 给 ArkTS 挂载 |
| 节点创建 | LottieXcomponentNode |
创建 XComponent、布局、生成渲染树、调度渲染任务 |
| 帧驱动 | Animator |
状态机 + 帧率控制 + 帧事件回调 |
| 省电 | ShouldSkipFrame |
不可见时跳过绘制 |
| 释放 | DisposeHandleOnUIThread |
UI 线程安全销毁节点 |
核心结论 :LottieView 只是声明式配置,真正的渲染由 LottieXcomponentNode(节点与绘制)和 Animator(帧驱动与状态机)在 native 侧完成 。前台的声明式配置通过 LottieContext 桥接到后厨,后厨按帧率一帧一帧画到 XComponent 的 surface 上。
对使用者的三条实用结论:
- 多动画同屏时,让
ShouldSkipFrame生效。不可见的动画会被自动跳过绘制,这是 lottie-turbo 比一代 Lottie 流畅的关键原因。 - 销毁组件前必须先
controller.stop()。DisposeHandleOnUIThread要求在 UI 线程释放,先停动画再销毁,避免DisposeLottieNode崩溃。 - 要硬件加速就用
texture渲染模式 (API 18+)。默认是 surface 模式,texture模式能利用 GPU 加速渲染。
下一篇讲缓存体系:memory_cache / file_cache / generator_key 怎么避免重复解析 JSON、LottieCache 的结构是什么、以及预加载是怎么让"滑回去的动画秒出"的。
项目地址:lottie-turbo