可用于在移动设备上加载和渲染 Lottie 动画,支持解析 After Effects 导出的 JSON 动画,采用声明式语法创建,具备并行化能力,提供丰富控制功能和事件监听,适配多 API 版本。【此简介由AI生成】
Access rate limit exceeded. Please log in to continue.
lottie-turbo
This project is developed based on lottie-turbo.
Table of Contents
- Overview
- Demo
- How to Install
- Constraints and Limitations
- Getting Started
- How to Use
- API Reference
- Comparison with Lottie
- Differences from Upstream rlottie
- Build Configuration
- About Obfuscation
- Remaining Issues
- Directory Structure
- How to Contribute
- License
Overview
lottie-turbo is an animation library for OpenHarmony. It can parse animations in JSON format exported by Adobe After Effects via the Bodymovin plugin and render them locally on mobile devices. Built with a declarative syntax, it features parallelization capabilities, making it suitable for scenarios where applications need to load Lottie animations.
Demo

How to Install
ohpm install @ohos/lottie-turbo
For more information on OpenHarmony ohpm environment configuration, please refer to How to Install OpenHarmony HAR.
Version Compatibility Note
Version 1.0.2-rc.1 and below only support devices with API16 and above, while version 1.0.2 is compatible with devices with API12 and above.
Constraints and Limitations
Compatibility
Verified on the following versions:
- OpenHarmony API version >=15.
Permission Requirements
When loading animations via network paths (URI), the application must declare ohos.permission.INTERNET in the module.json5 file's requestPermissions field. For local animations loaded from $rawfile or sandbox paths, no permission is required.
Getting Started
Simple Example
import { LottieController, LottieView } from '@ohos/lottie-turbo';
@Entry
@Component
struct Load {
private controller: LottieController = new LottieController();
build() {
Column() {
LottieView({
lottieId: "lottie1", // Animation ID, which must be unique.
loop: true, // Whether to loop the playback. The default value is true. It is optional.
autoplay: true, // Whether to play the animation automatically. The default value is true. It is optional.
autoSkip: true, // Whether to automatically skip rendering when the animation is invisible. The default value is true. It is optional.
path: $rawfile('common/lottie/grunt.json'), // Play the animation via rawfile.
// path: "https://cdn.lottielab.com/l/7Zgk9iuQxmZ3tD.json", // Play the animation via URI.
// Play the animation via the animation JSON string (string type). Its priority is higher than that of path.
// animationData: '{"v":"5.5.2","fr":60,"ip":0,"op":60,"w":512,"h":512,"ddd":0,"assets":[{"id":"Aa19853e5c3b98a7b8dde147916d26f78","h":114,"w":114,"u":"","p":"https://raw.gitcode.com/openharmony-sig/lottie_turbo/blobs/205ad8b5a8a42e8762fbe4899b8e5e31ce822b8b/startIcon.png","e":1}],"layers":[{"ddd":0,"ty":2,"sr":1,"ks":{"a":{"k":[0,0],"a":0},"p":{"k":[{"t":0,"s":[0,0,0],"i":{"x":[0.75],"y":[0.75]},"o":{"x":[0.25],"y":[0.25]}},{"t":60,"s":[400,400],"i":{"x":[0.75],"y":[0.75]},"o":{"x":[0.25],"y":[0.25]}}],"a":1},"s":{"k":[100,100],"a":0},"r":{"k":0,"a":0},"o":{"k":100,"a":0},"sk":{"k":0,"a":0},"sa":{"k":0,"a":0}},"ao":0,"ip":0,"op":60,"st":0,"bm":0,"ind":0,"refId":"Aa19853e5c3b98a7b8dde147916d26f78"}]}',
controller: this.controller, // Lottie animation controller
})
.width('50%')
.height(160)
.backgroundColor(Color.Gray)
.onClick(() => {
this.controller.togglePause(); // Pause the animation.
})
}
.height('100%')
.width('100%')
}
}
Supplementary Example
import { LottieView, LottieController, LottieListener, lottie } from '@ohos/lottie-turbo';
@Entry
@Component
struct Index {
private controller: LottieController = new LottieController(); // Animation controller
// Event listener
private listener: LottieListener = new LottieListener({
onEnterFrame: () => { // Callback for starting frame rendering
this.updateAllStates()
},
onLoopComplete: () => { // Callback triggered when an animation loop completes.
console.info("lottie complete");
this.playCount = this.controller?.playCount;
this.totalPlayedCount += 1;
},
onComplete: () => { // Callback triggered when an animation ends.
this.log += "lottie1 event complete\r\n"
},
onDestroy: () => { // Callback triggered when an animation is destroyed.
console.info("lottie destroy");
},
onDOMLoaded: () => { // Callback triggered when an animation is loaded (before playback starts).
console.info("lottie DOMLoaded");
},
onDataReady: () => { // Callback triggered when animation data is initialized.
this.log += "lottie1 event data_ready\r\n"
},
})
build() {
...
LottieView({
loop: true, // Whether to loop.
autoplay: true, // Whether to play automatically.
autoSkip: true, // Whether to automatically skip rendering when the animation is invisible.
lottieId: "lottie1" + this.getUniqueId(), // Set the unique ID.
contentMode: 'Contain', // Fill mode.
path: $rawfile('common/lottie/animation.json'), // Animation path.
frameRate: 30, // Playback frame rate. The value ranges from 1 to 120 Hz.
controller: this.controller, // Animation controller
initialSegment: [30, 150], // Initial frame range for playback.
listener: this.listener, // Event listener.
useCache: true, // Whether to use the cache.
setImageAssetDelegate: [["refid", "uri" ]]// Replace image resources (supporting Base64 URI ).
})
Button("Global Control")
.onClick(() => {
lottie.play(); // Play globally.
lottie.pause(); // Pause globally.
lottie.stop(); // Stop globally.
lottie.destroy(); // Destroy globally.
lottie.togglePause();// Pause/Play globally.
lottie.setSpeed(1); // Set the global playback speed.
lottie.setDirection(1); // Set the global playback direction (1: forward, -1: reverse).
lottie.setFrameRate(30);// Set the global playback frame rate.
lottie.clearFileCache("");// Clear the cache of a single file. If no parameter is passed, the cache of all files is cleared.
lottie.clearCache();// Clear the memory cache.
lottie.resizeCache(10, 10 * 1024 * 1024);// Reset the memory cache size.
lottie.resizeFileCache(10, 1024*1024);// Reset the file cache size.
lottie.removeCache("path")// Remove the memory cache by key.
})
Button("Single Control")
.onClick(() => {
this.controller.play(); // Play
this.controller.stop(); // Stop
this.controller.pause(); // Pause
this.controller.destroy(); // Destroy
this.controller.setSpeed(1); // Set the playback speed.
this.controller.goToAndPlay(250,true); // Jump to frame 250 and play (unit: ms).
this.controller.goToAndStop(250,true); // Jump to frame 250 and stop (unit: ms).
this.controller.setDirection(1); // Set the playback direction (1: forward; -1: reverse).
this.controller.setSegment(350, 0); // Set the frame range during animation playback.
this.controller.setSubframe(true); // Set whether to play the animation in interpolated frame mode (default: true).
this.controller.playSegments([[5,15],[20,30]],false);// Set the next playback to be performed according to segments. The setting takes effect immediately if the value is true.
this.controller.changeColor("**", [255, 0, 0, 1]); // Change RGBA animation color by layer name.
this.controller.togglePause() // Pause/Play.
this.controller.setFrameRate(30) // Set the playback frame rate.
this.controller.setContentMode("Contain"); // Set the filling mode. The options are Fill, Cover, Top, Bottom, Contain, AdaptiveHeight and AdaptiveWidth.
this.controller.reload({
path: "https://kjstorage.360buyimg.com/cms-file/1_eec97231.zip"
})
// Register a listener.
this.controller.addEventListener('drawFrame', (): void => {
this.log += "add lottie event drawFrame\r\n"
});
this.controller.removeEventListener('drawFrame'); // Remove the listener.
this.controller.triggerEvent("drawFrame"); // Forcibly trigger the callback.
//
})
...
}
// By default, destruction is automatically triggered when the LottieView component is destroyed.
aboutToDisappear(): void {
}
}
Precautions
-
- By default, destruction is automatically triggered when the page is about to disappear.
-
- Note that lottieId must be unique. If not configured, it is automatically generated randomly.
How to Use
To start off, get required data prepared.
Lottie animations are created in Adobe After Effects and exported with Bodymovin as JSON files.
When creating an animation in Adobe After Effects, you need to set the animation width (w), animation height (h), bodymovin version (v), frame rate (fr), start frame (ip), end frame (op), static resource information (assets), and layer information (layers).
For demo testing, you can use the JSON files provided in the project example.
1. Importing Component
import { lottie } from '@ohos/lottie-turbo'
2. Importing Animation Resources
(1) Load animations from local files.
LottieView({
path: $rawfile('common/lottie/animation.json'), // Animation path.
})
Path resources are stored in entry/src/main/resources/rawfile.
(2) Load animations from network resources.
LottieView({
path: "https://cdn.lottielab.com/l/7Zgk9iuQxmZ3tD.json", // Network path.
})
(3) Load animations from JSON strings.
LottieView({
animationData: '{"v":"5.5.2","fr":60,"ip":0,"op":60,"w":512,"h":512,"ddd":0,"assets":[{"id":"Aa19853e5c3b98a7b8dde147916d26f78","h":114,"w":114,"u":"","p":"https://raw.gitcode.com/openharmony-sig/lottie_turbo/blobs/205ad8b5a8a42e8762fbe4899b8e5e31ce822b8b/startIcon.png","e":1}],"layers":[{"ddd":0,"ty":2,"sr":1,"ks":{"a":{"k":[0,0],"a":0},"p":{"k":[{"t":0,"s":[0,0,0],"i":{"x":[0.75],"y":[0.75]},"o":{"x":[0.25],"y":[0.25]}},{"t":60,"s":[400,400],"i":{"x":[0.75],"y":[0.75]},"o":{"x":[0.25],"y":[0.25]}}],"a":1},"s":{"k":[100,100],"a":0},"r":{"k":0,"a":0},"o":{"k":100,"a":0},"sk":{"k":0,"a":0},"sa":{"k":0,"a":0}},"ao":0,"ip":0,"op":60,"st":0,"bm":0,"ind":0,"refId":"Aa19853e5c3b98a7b8dde147916d26f78"}]}',
// The priority of animationData is higher than that of path.
})
(4) Load animations from the sandbox path.
LottieView({
path: '/data/storage/el2/base/haps/entry/files/xxxx.json', // Sandbox path.
})
3. Configuring LottieView
LottieView supports common ArkUI settings.
LottieView({
path: $rawfile('common/lottie/grunt.json'), // Play the animation via rawfile.
})
.width('50%') // Set the width.
.height(160) // Set the height.
.backgroundColor(Color.Gray) // Set the background color.
// Register a listener for click events.
.onClick(() => {
})
4. Using LottieView
For details, see the simple example in "Getting Started".
5. Pausing Animation Playback
lottie.play() // Play all animations.
lottie.play('animation1') // Play animation1.
this.controller.play() // Play the animation bound to this.controller.
lottie.stop() // Stop all animations.
lottie.stop('animation1') // Stop animation1.
this.controller.stop() // Stop the animation bound to this.controller.
lottie.pause() // Pause all animations.
lottie.pause('animation1') // Pause animation1.
this.controller.pause() // Pause the animation bound to this.controller.
lottie.togglePause() // Switch the playback state between running and paused for all animations.
lottie.togglePause('animation1') // Pause or play animation1.
this.controller.togglePause() // Toggle the playback state between running and paused for the animation bound to this.controller.
6. Setting Playback Speed
Note: If the speed is greater than 0, the animation plays forwards. If the speed is less than 0, the animation plays backwards. If the speed is 0, the animation is paused. If the speed is 1.0 or -1.0, the animation plays at the normal speed.
lottie.setSpeed(1) // Set the speed for all animations.
lottie.setSpeed(1,'animation1') // Set the speed for animation1.
this.controller.setSpeed(1) // Set the speed for animation bound to this.controller.
7. Setting Playback Direction
Note: The value 1 indicates forward, and -1 indicates backward.
lottie.setDirection(1) // Set the playback direction for all animations.
lottie.setDirection(1,'animation1') // Set the playback direction for animation1.
this.controller.setDirection(1) // Set the playback direction for the animation bound to this.controller.
8. Destroying Animations
Note: When the page is not displayed or exits, the animation needs to be destroyed.
By default, this.controller.destroy is called in aboutToDisappear() of LottieView.
lottie.destroy() // Destroy all animations.
lottie.destroy('animation1') // Destroy animation1.
this.controller.destroy('animation1') // Destroy the animation with the specified name.
9. Jumping to Specific Animation
Note: The second parameter specifies whether to control by frame or time (in milliseconds). The value true means to control by frame, and false (default) means to control by time.
this.controller.goToAndPlay(250,true) // Jump to frame 250 and play the animation.
this.controller.goToAndPlay(12000,false) // Jump to 12000 ms and play the animation.
this.controller.goToAndStop(250,true) // Jump to frame 250 and stop the animation.
this.controller.goToAndStop(5000,false) // Jump to 5000 ms and stop the animation.
10. Playing Animation Segments
// Set an animation segment to limit the frame range for animation playback.
this.controller.setSegment(5,15);
// Play an animation segment. If the second parameter is set to true, the animation segment takes effect immediately. If the second parameter is set to false, the animation segment takes effect in the next loop.
this.controller.playSegments([[5,15],[20,30]],true)
// Reset animation segments so that the animation plays from the start frame.
// The value true indicates the setting takes effect immediately, and false indicates that the setting takes effect upon the next playback.
this.controller.resetSegments(true);
11. Listening for Animation Events
The following table lists the events that can be listened for.
| No. | Event Name | Description |
|---|---|---|
| 1 | enterFrame | Triggered when frame rendering starts. |
| 2 | drawFrame | Triggered when frame rendering is complete. |
| 3 | loopComplete | Triggered when one loop completes. |
| 4 | complete | Triggered when playback completes. |
| 5 | segmentStart | Triggered when a segment starts playing. |
| 6 | destroy | Triggered when the animation is destroyed. |
| 7 | config_ready | Triggered when configuration is ready. |
| 8 | data_ready | Triggered when data parsing completes. |
| 9 | DOMLoaded | Triggered when component is added to DOM. |
| 10 | data_failed | Triggered when data loading fails (abnormal JSON file). |
| 11 | loaded_images | Triggered when image data is loaded. |
| 12 | playStart | Triggered when playback starts (fires once when state switches from paused/stopped to playing; not affected by first-frame static rendering). |
| 13 | cancel | Triggered when playback is actively stopped via stop() (fires only when stopping from a playing state; not confused with natural completion). |
(1) Configuring Listener When Creating LottieView
// Configure the listener.
private listener: LottieListener = new LottieListener({
onDrawFrame: () => {
console.info("onDrawFrame");
}
})
// Bind the listener.
LottieView({
listener: this.listener
})
(2) Dynamically Adding Listeners
// Add event listeners.
this.controller.addEventListener('loopComplete', (): void => {
console.info("loopComplete");
})
(3) Dynamically Removing Listeners
// Remove event listeners. You can set the callback function after the execution is complete.
this.controller.removeEventListener('loopComplete', (): void => {
// Call this function after the removal.
console.info("loopComplete");
})
(4) Precautions
- DOMLoaded event
-
With parallel loading, animation data parsing may not be complete when the DOMLoaded event is triggered, making animation controls ineffective.
-
To ensure image resources are loaded before playback starts, use the loaded_images event.
12. Changing Animation Color
Currently, only fill layers and shape layers are supported.
(1) Non-key Frame
// Note: The first parameter is the layer name, and the second parameter is the RGB or RGBA value of the color.
// The color value ranges from 0 to 255, and the transparency value ranges from 0 to 1.0.
// Use "**" to change the colors of all layers.
this.controller.changeColor("**.Layer 1 Outlines.**",[255,150,203]) // Change the color of an element without transparency.
this.controller.changeColor("**.Layer 1 Outlines.**",[255,150,203,1.0]) // Change the color of an element with transparency.
(2) Key Frame and Gradient Color
// Note: The first parameter indicates the layer name, and the second and third parameters indicate the start and end RGB or RGBA values of the key frame.
// The color value ranges from 0 to 255, and the transparency value ranges from 0 to 1.0.
// Use "**" to change the colors of all layers.
this.controller.changeColor("**.Layer 1.**",[255,0,0],[0,0,255]) // Change the color of a key frame, without transparency.
this.controller.changeColor("**.Layer 1.**",[255,0,0,0],[0,0,255,1]) // Change the color of a key frame, with transparency.
13. Replacing Resource Files
The following provides an API to modify image resources in JSON animations before loading.
"assets": [
{
"id": "blep",
"h": 114,
"w": 114,
"u": "",
"p": "data:image/png;",
"e": 1
}
]
// Use the setImageAssetDelegate parameter in lottieView to replace image resources (supporting Base64 and URI Sandbox Path).
// refId corresponds to the "id" field under "assets" in the JSON animation, as shown in the preceding example.
LottieView({
path: $rawfile('common/lottie/data_url.json'),
setImageAssetDelegate: [
["refid", "base64" ],
["refid", "uri"],
["refid", "/data/storage/el2/base/haps/entry/files/xxxx.png"]
]
})
14. Loading Cross-Module Animations
For multiple modules, the capability of reading resources across modules is provided in the scenario where resources need to be invoked across packages.
(1) Loading Module
Add the specified module to dependencies in oh-package.json.
(2) Loading LottieView
Use $rawfile in the path attribute with the module name in square brackets to reference cross-module resources:
LottieView({
loop: true,
autoplay: true,
path: $rawfile('[entry].robotYoga.json') // Replace entry with the module name.
})
15. Changing Animations
The following APIs are provided for changing the animation displayed on the same component.
- path?: string | Resource
- animationData?: string;
- loop?: boolean | number
- autoplay?: boolean
- initialSegment?: AnimationSegment
- contentMode?: string
- frameRate?: number
- setImageAssetDelegate?: ImageAssetDelegate[];
- imagePath?: string;
- resManager?: resmgr.ResourceManager;
For details about other parameters, see the description of LottieView. The resManager parameter is added.
resManager: resource manager. This parameter is optional. It is used when the initial animation is not in the same module as the animation. The usage is as follows:
(1) New animation is in the same module as the original.
this.controller.reload({
loop: true,
autoplay: true,
path: $rawfile('common/lottie/animation.json')
})
(2) New animation is in a different module than the original.
this.controller.reload({
loop: true,
autoplay: true,
path: $rawfile('[lalhan].robotYoga.json'),
resManager: (await application.createModuleContext(getContext(this),'lalhan')).resourceManager // Replace entry with the corresponding module name.
})
16. Determining Animation Complexity
Animation playback power consumption and complexity are closely related to the number of drawing commands. lottie-turbo provides a demo to calculate drawing commands per frame.
Compile in debug mode and switch animations on the RenderInfo page and tap single-frame rendering. Then you can search logs for RenderInfo to find the following information:
The default mode for this project is release mode. If you need to adjust it to debug, you need to annotate the "arguments": "-DCMAKE_BUILD_TYPE=RelWithDebInfo" in the library/build-profile.json5 path
Lottie RenderInfo::Number of Render Path:75 // Path rendering
Lottie RenderInfo::Number of Render Text:0 // Text rendering
Lottie RenderInfo::Number of Render Image:0 // Image rendering
Lottie RenderInfo::Number of Render SaveLayer:1 // Layer saving
Lottie RenderInfo::Number of Render Mask:0 // Mask rendering
Lottie RenderInfo::Number of Render StrokeEff:0 // Stroke rendering
Lottie RenderInfo::Number of Render TritoneEff:0 // Tritone rendering
Lottie RenderInfo::Number of Render TintEff:0 // Tint effect rendering
Lottie RenderInfo::Number of Render FillEff:0 // Filling rendering
Lottie RenderInfo::Number of Render BlurEff:0 // Blur rendering
Note: BlurEff (Gaussian blur) has a significant performance impact. Consider optimizing or replacing this effect if possible.
17. Rendering Animations to Image Data
lottie-turbo provides an off-screen rendering API (renderToImage) to convert Lottie animations to image data.
Lottie off-screen rendering produces bitmaps with return type ArrayBuffer. The following parameters are included:
- lottie: Lottie animation to render (supporting raw files/urls/strings).
- frameNum: Frame number (supporting decimals).
- width: width.
- height: height.
- resManager?: resource manager (supporting raw files).
(1) Raw File Type
When using a resource path, set resManager with the module name containing the resource:
lottie.renderToImage($rawfile('common/lottie/float Test.json'), 1, 200, 200,
(await application.createModuleContext(getContext(this), 'entry')).resourceManager)
(2) URL Type
lottie.renderToImage('https://cdn.lottielab.com/l/7Zgk9iuQxmZ3tD.json', 1, 300, 300)
(3) String Type
lottie.renderToImage('{"v":"5.5.2","fr":60,"ip":0,"op":60,"w":512,"h":512,"ddd":0,"assets":[{"id":"Aa19853e5c3b98a7b8dde147916d26f78","h":114,"w":114,"u":"","p":"https://raw.gitcode.com/openharmony-sig/lottie_turbo/blobs/205ad8b5a8a42e8762fbe4899b8e5e31ce822b8b/startIcon.png","e":1}],"layers":[{"ddd":0,"ty":2,"sr":1,"ks":{"a":{"k":[0,0],"a":0},"p":{"k":[{"t":0,"s":[0,0,0],"i":{"x":[0.75],"y":[0.75]},"o":{"x":[0.25],"y":[0.25]}},{"t":60,"s":[400,400],"i":{"x":[0.75],"y":[0.75]},"o":{"x":[0.25],"y":[0.25]}}],"a":1},"s":{"k":[100,100],"a":0},"r":{"k":0,"a":0},"o":{"k":100,"a":0},"sk":{"k":0,"a":0},"sa":{"k":0,"a":0}},"ao":0,"ip":0,"op":60,"st":0,"bm":0,"ind":0,"refId":"Aa19853e5c3b98a7b8dde147916d26f78"}]}',
1, 300, 300)
18. useImageCache Image Cache Description
This attribute is only suitable for displaying scenes with small animation areas and a large number of scenes (1vp is approximately equal to 3.5px)
Taking a 100px x 100px image with a total of 180 frames as an example, an animation requires a consumption of 100x100x4x180=7200000B ≈ 7MB
A 100vp * 100vp image will occupy 350x350x4x180 ≈ 84MB of memory. For specific display, please refer to the demo: UseImageCache.ets
19. Separation of tree-based and animation parsing
Using the lottie.createLottieNode interface supports the separation of the tree and loading animations, enabling pre-rendering. Note:
-
- It is necessary to actively call controller.destroy, otherwise memory leaks may occur;
-
- The autoSkip function is not working, and it cannot stop rendering when it is not visible. If this ability is required, it needs to be implemented manually;
-
- If files in the rawfile directory are used, resManager is a required attribute;
struct Load {
private rootSlot = new NodeContent();
private controller: LottieController = new LottieController();
@State isShow: boolean = false;
aboutToAppear(): void {
lottie.createLottieNode({
loop: true,
autoplay: true,
path: $rawfile('common/lottie/grunt.json'),
contentMode: 'Contain',
controller: this.controller,
resManager: this.getUIContext().getHostContext()?.resourceManager
//use in same module,resManager: this.getUIContext().getHostContext()?.resourceManager
//use in different module,resManager: (await application.createModuleContext(getContext(this),'lalhan')).resourceManager
},this.rootSlot)
}
aboutToDisappear(): void {
//must destroy
this.controller?.destroy()
}
build() {
Column() {
Column() {
if (this.isShow) {
ContentSlot(this.rootSlot)
} else {
Text("null")
}
}.width(200)
.height(200)
Button("load")
.width("35%")
.onClick(() => {
this.isShow = !this.isShow;
})
}
.height('100%')
.width('100%')
}
}
20. Set Layer Properties
LottieController.setLayerProperties dynamically overrides text, fill, stroke, transform, repeater, precomp time remap, image bitmap, shape geometry, gradient, and related properties.
- Parameters: the first argument is the layer name in the Lottie JSON (
nmfield); the second isLayerProperties. - Return values: 0 - success, 1 - invalid parameter, 2 - animation not loaded, 3 - property parse failed, 4 - layer not found.
Notes:
-
textLayerPropertiesis an object array; each element maps to one keyframe slot;{}means no override for that slot.
-
fillProperties,strokeProperties,transformProperties,repeaterProperties,shapeProperties, andtimeRemapPropertiesare single objects whose fields are independent slot arrays aligned with keyframe segments of the corresponding property; array length per field follows the keyframe segment count in JSON and need not match across fields;nullin a slot means no override for that segment.
-
- For
gradientProperties, the outer array index is the color stop;gradientColorandgradientOpacityinside each stop are keyframe slot arrays.
- For
-
- When a field is passed as a single-element array (e.g.
fillOpacity: [90]), it applies only to keyframe segment 0; if the property has no keyframes, it applies for the full duration.
- When a field is passed as a single-element array (e.g.
-
imagePropertiesis a one-shot bitmap replacement and does not use keyframe slots.
// Currently supported properties
export interface LayerProperties {
// Text layer properties
textLayerProperties?: TextLayerProperties[];
// Fill layer properties
fillProperties?: FillProperties;
// Stroke layer properties
strokeProperties?: StrokeProperties;
// Transform layer properties
transformProperties?: TransformProperties;
// Repeater
repeaterProperties?: RepeaterProperties;
// Precomp time remap
timeRemapProperties?: number[];
// Image layer bitmap replacement
imageProperties?: ImageProperties;
// Shape geometry
shapeProperties?: ShapeProperties;
// Gradient fill/stroke
gradientProperties?: GradientStopProperties[];
}
export interface ColorConfig {
// Red component, range [0 - 1]
r: number;
// Green component, range [0 - 1]
g: number;
// Blue component, range [0 - 1]
b: number;
}
export interface PointConfig {
// X coordinate
x: number;
// Y coordinate
y: number;
}
// w/h use Lottie units; percentage for scale; Lottie units for shape geometry size.
export interface SizeConfig {
// Width component
w: number;
// Height component
h: number;
}
1. Text Layer Properties (textLayerProperties)
export interface TextLayerProperties {
// Text content
text?: string;
// Fill color
fillColor?: ColorConfig;
// Fill opacity, range [0 - 100]
fillOpacity?: number;
// Stroke color
strokeColor?: ColorConfig;
// Stroke opacity, range [0 - 100]
strokeOpacity?: number;
// Font size
fontSize?: number;
// Tracking
tracking?: number;
// Font family name
typeface?: string;
}
(1) Non-keyframe
// Single-slot override (full duration when no keyframes; segment 0 only when keyframes exist)
// Pass only the fields you need; omitted fields keep JSON values
let result: number = this.controller.setLayerProperties("LayerName", {
textLayerProperties: [{
text: 'New Text',
fillColor: { r: 0.38, g: 0.59, b: 0.0 },
fillOpacity: 50, // optional, range 0-100
strokeColor: { r: 0.93, g: 0.17, b: 0.55 },
strokeOpacity: 80, // optional
fontSize: 48, // optional
tracking: 2, // optional
typeface: 'FontName' // optional, must match fName in JSON fonts.list
}]
});
(2) Keyframe
// Note: array index maps to keyframe slot; {} means no override for that slot
let result: number = this.controller.setLayerProperties("LayerName", {
textLayerProperties: [
{ text: 'Frame 1' },
{},
{ text: 'Frame 3', fillColor: { r: 1, g: 0, b: 0 }, fillOpacity: 100 }
]
});
// Override font size in one slot only: { fontSize: 56 }; use {} for other slots
2. Fill / Stroke Layer Properties (fillProperties, strokeProperties)
export interface FillProperties {
// Fill color
fillColor?: ColorConfig[];
// Fill opacity, range [0 - 100]
fillOpacity?: number[];
}
export interface StrokeProperties {
// Stroke color
strokeColor?: ColorConfig[];
// Stroke opacity, range [0 - 100]
strokeOpacity?: number[];
// Stroke width
strokeWidth?: number[];
}
(1) Non-keyframe
// Single-slot override (full duration when no keyframes; segment 0 only when keyframes exist)
// Each field is an independent array; pass only what you need
let result: number = this.controller.setLayerProperties("LayerName", {
fillProperties: {
fillColor: [{ r: 0.2, g: 0.7, b: 0.3 }],
fillOpacity: [90] // optional, range 0-100
},
strokeProperties: {
strokeColor: [{ r: 0.1, g: 0.2, b: 0.9 }],
strokeOpacity: [100], // optional
strokeWidth: [6] // optional
}
});
(2) Keyframe
// Note: field array index maps to keyframe slot; null means no override for that segment
// Array length per field follows keyframe segment count in JSON and need not match
let result: number = this.controller.setLayerProperties("LayerName", {
fillProperties: {
fillColor: [{ r: 0.2, g: 0.7, b: 0.3 }, null, { r: 1, g: 0, b: 0 }], // color, 3 segments
fillOpacity: [90, 50] // opacity, 2 segments
},
strokeProperties: {
strokeWidth: [6] // stroke width single slot, segment 0 only
}
});
3. Transform Layer Properties (transformProperties)
export interface TransformProperties {
// Anchor point
anchor?: PointConfig[];
// Position (non-separated p)
position?: PointConfig[];
// Scale, in percent
scale?: SizeConfig[];
// Rotation, in degrees
rotation?: number[];
// Opacity, range [0 - 100]
opacity?: number[];
// Separated position X
positionX?: number[];
// Separated position Y
positionY?: number[];
// Skew angle (degrees), range 0-85
skew?: number[];
// Skew axis angle (degrees), range 0-360; 0 along X, 90 along Y
skewAxis?: number[];
// 3D rotation around X axis, in degrees
rotationX?: number[];
// 3D rotation around Y axis, in degrees
rotationY?: number[];
// 3D rotation around Z axis, in degrees (Lottie rz)
rotationZ?: number[];
}
(1) Non-keyframe
// Single-slot override (full duration when no keyframes; segment 0 only when keyframes exist)
// Each field is an independent array corresponding to the keyframe segments of that transform sub-property
let result: number = this.controller.setLayerProperties("LayerName", {
transformProperties: {
position: [{ x: 120, y: 80 }], // merged 2D position (non-separated Lottie p)
scale: [{ w: 110, h: 110 }], // percent; 100 means 100%
rotation: [15], // 2D rotation, degrees
opacity: [85] // optional, range 0-100
}
});
// Separated position: use positionX / positionY when JSON p is separated
// If position is also passed, the engine prefers position and ignores positionX / positionY
let result2: number = this.controller.setLayerProperties("LayerName", {
transformProperties: {
positionX: [120],
positionY: [80]
}
});
// Skew: dynamic override when JSON transform contains sk/sa (2D or 3D, not 3D-only)
let result3: number = this.controller.setLayerProperties("LayerName", {
transformProperties: {
skew: [10],
skewAxis: [0]
}
});
// Note: shear uses tan(skew°); larger angles stretch the shape more (85° is the spec max). skewAxis applies only when skew > 0 and sets shear direction (0° along X, 90° along Y).
// 3D rotation: only when JSON is 3D transform (layer ddd and rx/ry/rz present)
let result4: number = this.controller.setLayerProperties("LayerName", {
transformProperties: {
rotationX: [30],
rotationY: [15],
rotationZ: [45] // Lottie rz; stacks with rotation
}
});
(2) Keyframe
// Note: field array index maps to keyframe slot; null means no override for that segment
// Each field resolves keyframe segments independently; array lengths need not match
let result: number = this.controller.setLayerProperties("LayerName", {
transformProperties: {
position: [{ x: 0, y: 0 }, null, { x: 200, y: 100 }], // p, 3 segments
opacity: [100, 50], // o, 2 segments
rotation: [45] // r, single slot
}
});
// layerName may also match a shape group name to target that group's transform (see TransformRepeaterDynamicDemo)
4. Repeater (repeaterProperties)
export interface RepeaterProperties {
// Copy count, 0–512; 0 hides all copies
copies?: number[];
// Offset
offset?: number[];
// First copy opacity, range [0 - 100]
startOpacity?: number[];
// Last copy opacity, range [0 - 100]
endOpacity?: number[];
}
(1) Non-keyframe
// Single-slot override (full duration when no keyframes; segment 0 only when keyframes exist)
// layerName must match a shape layer that contains a Repeater modifier
let result: number = this.controller.setLayerProperties("LayerName", {
repeaterProperties: {
copies: [6], // copy count, 0–512; 0 hides all copies
offset: [0.15], // optional
startOpacity: [100], // optional, range 0-100
endOpacity: [40] // optional
}
});
(2) Keyframe
// Note: field array index maps to keyframe slot; null means no override for that segment
// Array length per field follows keyframe segment count in JSON and need not match
let result: number = this.controller.setLayerProperties("LayerName", {
repeaterProperties: {
copies: [3, 8], // copies, 2 segments
offset: [0, null, 0.5], // offset, 3 segments
endOpacity: [30] // endOpacity, single slot
}
});
5. Precomp Time Remap (timeRemapProperties)
Maps the internal timeline of a precomp layer to a specified time (seconds). Type is number[]; each index corresponds to a tm keyframe segment in the JSON timeline data.
(1) Non-keyframe
// Single-slot override (full duration when no keyframes; segment 0 only when keyframes exist)
// layerName must be a precomp layer with time remap enabled (tm field present)
let result: number = this.controller.setLayerProperties("PrecompLayer", {
timeRemapProperties: [1.5] // map to 1.5 seconds on the child comp timeline
});
// Clear override and restore default JSON time progression
let result2: number = this.controller.setLayerProperties("PrecompLayer", {
timeRemapProperties: []
});
(2) Keyframe
// Note: array index maps to tm keyframe slot; null means no override for that segment
// Array length follows tm keyframe segment count in JSON
let result: number = this.controller.setLayerProperties("PrecompLayer", {
timeRemapProperties: [0, null, 2.0] // tm, 3 segments: segment 0 -> 0s, segment 2 -> 2s
});
6. Image Layer Bitmap Replacement (imageProperties)
export interface ImageProperties {
// Bitmap: sandbox absolute path or data:URL; HTTP(S) must be downloaded locally first
bitmap?: string;
}
One-shot replacement of the target image layer bitmap for the full duration; no keyframe slots. layerName must match the image layer nm.
// Sandbox local path
let result: number = this.controller.setLayerProperties("ImageLayer", {
imageProperties: {
bitmap: '/data/storage/el2/base/haps/entry/files/replace.png'
}
});
// data:URL (base64)
let result2: number = this.controller.setLayerProperties("ImageLayer", {
imageProperties: {
bitmap: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ...'
}
});
// http(s): download to a local path in your app first, then pass the sandbox path (URL not supported directly)
let localPath: string = '/data/storage/el2/base/haps/entry/files/downloaded.png'
let result3: number = this.controller.setLayerProperties("ImageLayer", {
imageProperties: { bitmap: localPath }
});
// Clear dynamic bitmap and restore original JSON asset
let result4: number = this.controller.setLayerProperties("ImageLayer", {
imageProperties: {}
});
7. Shape Geometry (shapeProperties)
export interface ShapeProperties {
// Rectangle size
rectangleSize?: SizeConfig[];
// Corner radius
cornerRadius?: number[];
// Ellipse size
ellipseSize?: SizeConfig[];
// Position
position?: PointConfig[];
// Polystar point count
polystarPoints?: number[];
// Polystar rotation, degrees
polystarRotation?: number[];
// Polystar inner radius
polystarInnerRadius?: number[];
// Polystar outer radius
polystarOuterRadius?: number[];
// Polystar inner roundness, range 0-100
polystarInnerRoundness?: number[];
// Polystar outer roundness, range 0-100
polystarOuterRoundness?: number[];
// Path
path?: PathConfig[];
}
// Dynamic path replacement
export interface PathConfig {
// Path point sequence
points?: PointConfig[];
// Whether closed
closed?: boolean;
}
(1) Non-keyframe
// Single-slot override (full duration when no keyframes; segment 0 only when keyframes exist)
// layerName must match shape layer or node name; pass only fields for geometry types present in JSON
// rectangleSize / ellipseSize use Lottie geometry units (not scale percent)
// Rectangle
let result: number = this.controller.setLayerProperties("ShapeLayer", {
shapeProperties: {
rectangleSize: [{ w: 120, h: 80 }],
cornerRadius: [12],
position: [{ x: 10, y: 20 }]
}
});
// Polystar
let result2: number = this.controller.setLayerProperties("ShapeLayer", {
shapeProperties: {
polystarPoints: [8],
polystarRotation: [15],
polystarInnerRadius: [30],
polystarOuterRadius: [70]
}
});
// Path
let result3: number = this.controller.setLayerProperties("ShapeLayer", {
shapeProperties: {
path: [{
closed: true,
points: [{ x: 0, y: 0 }, { x: 100, y: 0 }, { x: 50, y: 80 }]
}]
}
});
(2) Keyframe
// Note: field array index maps to keyframe slot; null means no override for that segment
// Array length per field follows keyframe segment count in JSON and need not match
let result: number = this.controller.setLayerProperties("ShapeLayer", {
shapeProperties: {
rectangleSize: [{ w: 100, h: 80 }, null, { w: 150, h: 90 }], // size, 3 segments
cornerRadius: [0, 12], // corner radius, 2 segments
position: [{ x: 0, y: 0 }] // position, single slot
}
});
8. Gradient Layer Properties (gradientProperties)
export interface GradientStopProperties {
// Gradient color
gradientColor?: ColorConfig[];
// Gradient opacity, range [0 - 100]
gradientOpacity?: number[];
}
For gradientProperties, the outer array index is the color stop; gradientColor and gradientOpacity inside each stop are arrays corresponding to keyframe slots (denoted by 'g'). Lengths are configured per JSON and are independent.
(1) Non-keyframe
// Single-slot two-stop gradient (full duration when no keyframes; segment 0 only when keyframes exist)
let result: number = this.controller.setLayerProperties("LayerName", {
gradientProperties: [
{ gradientColor: [{ r: 1, g: 0, b: 0 }], gradientOpacity: [100] }, // stop 0
{ gradientColor: [{ r: 0, g: 0, b: 1 }], gradientOpacity: [100] } // stop 1
]
});
(2) Keyframe
// Note: inner array index maps to g keyframe slot; null means no override for that segment
// gradientColor / gradientOpacity array lengths per stop need not match
let result: number = this.controller.setLayerProperties("LayerName", {
gradientProperties: [
{ gradientColor: [{ r: 1, g: 0, b: 0 }, null], gradientOpacity: [100] }, // stop 0
{ gradientColor: [{ r: 0, g: 0, b: 1 }], gradientOpacity: [100, null, 80] } // stop 1
]
});
21. Support decoding GIF images and retrieving the first frame as a static image
Modify image assets in the JSON animation before loading, allowing images to be replaced with GIF files.
LottieView({
path: $rawfile('common/lottie/data_url.json'),
setImageAssetDelegate: [
["refid", this.getUIContext().getHostContext()?.resourceDir + "/imageType/error404.gif"],
]
})
22. RenderMode Rendering Mode
lottie-turbo supports two rendering modes, configurable via the renderMode parameter.
(1) Surface Mode (Default)
Uses XComponent's Surface rendering method, which is the default rendering mode. When the renderMode parameter is not set or its value is not "Texture", Surface mode is automatically used.
Features:
- Rendering content is displayed on a separate layer
(2) Texture Mode
Uses XComponent's Texture rendering method.
Features:
- Rendering content is rendered as texture with other UI elements on the same layer
Note: Texture mode only works when API version ≥ 18 and renderMode parameter is set to "Texture". Otherwise, it will automatically fallback to Surface mode.
LottieView({
path: $rawfile('common/lottie/animation.json'),
renderMode: "Texture" // Set to Texture rendering mode
})
23. The animation fill mode supports AdaptiveWidth and AdaptiveHeight
LottieView supports common ArkUI settings.
LottieView({
lottieId: "lottie1", // Animation ID, which must be unique.
contentMode: 'AdaptiveWidth', // Adapt the width according to the component height and animation scale.
path: $rawfile('common/lottie/grunt.json'), // Play the animation via rawfile.
})
.height('40%') // Set the height.
.backgroundColor(Color.Gray) // Set the background color.
// Register a listener for click events.
.onClick(() => {
})
LottieView({
lottieId: "lottie2", // Animation ID, which must be unique.
contentMode: 'AdaptiveHeight', // Adapt the height according to the component width and animation scale.
path: $rawfile('common/lottie/grunt.json'), // Play the animation via rawfile.
})
.width('50%') // Set the width.
.backgroundColor(Color.Gray) // Set the background color.
// Register a listener for click events.
.onClick(() => {
})
API Reference
Components
| Name | Description | Type | Required | OpenHarmony Platform Support |
|---|---|---|---|---|
| LottieView | Lottie animation view component | struct | Yes | Yes |
Properties
| Name | Description | Type | Required | OpenHarmony Platform Support |
|---|---|---|---|---|
| lottieId | Unique ID within the application | string | No | Yes |
| path | Path to animation data file, supports JSON files and ZIP files | string | Resource | No | Yes |
| animationData | JSON format animation data, has higher priority than path | string | No | Yes |
| loop | Whether to loop playback / number of loops | boolean | number | No | Yes |
| autoplay | Whether to autoplay | boolean | No | Yes |
| autoSkip | Whether to skip drawing when animation is invisible, default is true | boolean | No | Yes |
| initialSegment | Overall frame range for initial animation resource playback | [number, number] | No | Yes |
| contentMode | Animation fill mode | string | No | Yes |
| renderMode | Animation Render mode | string | No | Yes |
| frameRate | Set render frame rate, range 1~120 | number | No | Yes |
| useCache | Whether to use cache, default is true | boolean | No | Yes |
| useImageCache | Whether to use image cache, only applicable for animations with small display areas | boolean | No | Yes |
| controller | Animation controller | LottieController | No | Yes |
| listener | Event listener | LottieListener | No | Yes |
| setImageAssetDelegate | Resource replacement function, format is [image resource ID, Base64/URI/sandbox path] | Array<[string, string]> | No | Yes |
| imagePath | Resource directory path | string | No | Yes |
| radius | Border radius | number | No | Yes |
| bgColor | Background color, default is 0 | number | No | Yes |
| imageProvider | Image load result provider, used to receive image resource load results of animations, independent of LottieListener.onLoadedImages | AnimationImageProvider | No | Yes |
API
LottieController Methods
| Name | Description | Type | Parameters | Return Value | Required | OpenHarmony Platform Support |
|---|---|---|---|---|---|---|
| play | Play animation | Method | None | void | No | Yes |
| pause | Pause animation | Method | None | void | No | Yes |
| stop | Stop animation | Method | None | void | No | Yes |
| togglePause | Toggle pause/play state | Method | None | void | No | Yes |
| destroy | Destroy animation | Method | None | void | No | Yes |
| goToAndPlay | Jump to specified frame or time and play | Method | value: number, isFrame?: boolean | void | No | Yes |
| goToAndStop | Jump to specified frame or time and stop | Method | value: number, isFrame?: boolean | void | No | Yes |
| setSegment | Set animation segment | Method | init: number, end: number | void | No | Yes |
| playSegments | Play specified segments | Method | segments: AnimationSegment | AnimationSegment[], forceFlag?: boolean | void | No | Yes |
| resetSegments | Reset animation segment | Method | forceFlag: boolean | void | No | Yes |
| setSpeed | Set playback speed | Method | speed: number | void | No | Yes |
| setDirection | Set playback direction | Method | direction: number | void | No | Yes |
| setSubframe | Set whether to use subframe playback | Method | useSubFrames: boolean | boolean | No | Yes |
| getDuration | Get animation duration | Method | inFrames?: boolean | number | No | Yes |
| triggerEvent | Force trigger specified event | Method | name: string | void | No | Yes |
| addEventListener | Add event listener | Method | name: string, callback: Function | void | No | Yes |
| removeEventListener | Remove event listener | Method | name: string, callback?: Function | void | No | Yes |
| changeColor | Change animation color | Method | layer: string, startColor: number[], endColor?: number[] | void | No | Yes |
| setContentMode | Set fill mode | Method | contentMode: string | void | No | Yes |
| setFrameRate | Set animation frame rate | Method | frameRate: number | void | No | Yes |
| reload | Reload animation | Method | config: ConfigType | void | No | Yes |
| setLayerProperties | Set layer properties | Method | layerName: string, properties: LayerProperties | number | No | Yes |
LottieController Properties
| Name | Description | Type | Required | OpenHarmony Platform Support |
|---|---|---|---|---|
| lottieId | Unique ID | string | Yes | Yes |
| isLoaded | Whether loaded | boolean | No | Yes |
| currentFrame | Current frame number, defaults to float | number | No | Yes |
| currentRawFrame | Current frame number, float | number | No | Yes |
| firstFrame | First frame number of current playing segment | number | No | Yes |
| totalFrames | Total frames of current playing segment | number | No | Yes |
| frameRate | Frame rate frame/s | number | No | Yes |
| frameMult | Frame rate frame/ms | number | No | Yes |
| playSpeed | Playback speed | number | No | Yes |
| playDirection | Playback direction | number | No | Yes |
| playCount | Number of completed playbacks | number | No | Yes |
| isPaused | Whether paused | boolean | No | Yes |
| autoplay | Whether to autoplay | boolean | No | Yes |
| loop | Whether to auto loop | boolean | number | No | Yes |
| timeCompleted | Number of frames played in current animation segment | number | No | Yes |
| segmentPos | Current animation segment sequence number | number | No | Yes |
| isSubframeEnabled | Whether to update animation frame rate as frequently as possible | boolean | No | Yes |
| segments | Current animation playing segment | AnimationSegment | AnimationSegment[] | No | Yes |
Global lottie Methods
| Name | Description | Type | Parameters | Return Value | Required | OpenHarmony Platform Support |
|---|---|---|---|---|---|---|
| play | Play animation | Method | lottieId?: string | void | No | Yes |
| pause | Pause animation | Method | lottieId?: string | void | No | Yes |
| stop | Stop animation | Method | lottieId?: string | void | No | Yes |
| togglePause | Toggle pause/play state | Method | lottieId?: string | void | No | Yes |
| destroy | Destroy animation | Method | lottieId?: string | void | No | Yes |
| setSpeed | Set playback speed | Method | speed: number, lottieId?: string | void | No | Yes |
| setDirection | Set playback direction | Method | direction: 1 | -1, lottieId?: string | void | No | Yes |
| setFrameRate | Set playback frame rate | Method | frameRate: number | void | No | Yes |
| clearFileCache | Clear file cache | Method | url?: string | void | No | Yes |
| resizeCache | Set memory cache container size | Method | size: number, capacity: number | void | No | Yes |
| resizeFileCache | Set file cache container size | Method | size: number, capacity: number | void | No | Yes |
| clearCache | Clear cache container | Method | None | void | No | Yes |
| removeCache | Remove cache by cache key | Method | path: string | void | No | Yes |
| renderToImage | Render a frame of animation as image data off-screen | Method | lottie: string | Resource, frameNum: number, width: number, height: number, resManager?: ResourceManager | ArrayBuffer | No | Yes |
| createLottieNode | Bind ContentSlot and LottieController | Method | config: AnimationConfig, content: Object | void | No | Yes |
Interfaces
AnimationImageProvider
Image load result provider, aligned with iOS AnimationImageProvider. It is used to receive the load results of image resources in animations, and is completely independent of LottieListener.onLoadedImages without interfering with each other. When set via the imageProvider property of LottieView, the callback is triggered when the animation loading process finishes, allowing the business to perceive the per-image load status.
| Name | Description | Type | Parameters | Return Value | OpenHarmony Platform Support |
|---|---|---|---|---|---|
| onImageLoadResult | Image load result callback. Reports the per-image load status when the animation loads successfully; reports __animation__ overall failure when the animation fails to load |
Method | result: ImageLoadResult | void | Yes |
ImageLoadResult
Image load result, provided via the AnimationImageProvider.onImageLoadResult callback.
| Name | Description | Type | Required | OpenHarmony Platform Support |
|---|---|---|---|---|
| success | Whether all images are loaded successfully. true means the animation loads successfully and all images are loaded successfully (failedImages/failedDetails are empty); false means the animation fails to load overall, or some/all images fail to load | boolean | Yes | Yes |
| failedImages | List of failed resource identifiers (animation file name preferred, falling back to refId; '__animation__' for empty path) |
string[] | Yes | Yes |
| failedDetails | Detailed information list of load failures | Array<ImageLoadFailureDetail> | Yes | Yes |
ImageLoadFailureDetail
Image load failure detail, the element type of the ImageLoadResult.failedDetails array.
| Name | Description | Type | Required | OpenHarmony Platform Support |
|---|---|---|---|---|
| refId | Resource reference ID, corresponding to refId in the JSON; the special value '__animation__' indicates an overall load failure (e.g., invalid JSON, ip>op), in which case reason describes the overall failure cause |
string | Yes | Yes |
| reason | Failure reason, possible values are listed in the table below | string | Yes | Yes |
reason values:
| reason Value | Description |
|---|---|
animation load failed |
Animation overall load failed (refId is '__animation__') |
refId not found |
refId not found in JSON assets |
base64 decode failed |
Failed to decode base64 data to binary |
base64 data empty |
base64 decoded successfully but data is an empty string |
image source create failed |
Failed to create ImageSource from image data |
image dimensions invalid |
Image dimensions are 0 or failed to obtain |
image decode failed |
Failed to decode ImageSource to PixelMap |
pixel read failed |
Failed to read PixelMap pixel data to VBitmap |
file not found |
Sandbox path file does not exist or cannot be opened |
download failed |
Network image download failed (HTTP error or empty response body) |
download data empty |
Download succeeded but response body data is empty |
Usage example:
import { LottieController, LottieView, AnimationImageProvider, ImageLoadResult } from '@ohos/lottie-turbo';
class ImageProviderImpl implements AnimationImageProvider {
private callback: (result: ImageLoadResult) => void;
constructor(callback: (result: ImageLoadResult) => void) {
this.callback = callback;
}
onImageLoadResult(result: ImageLoadResult): void {
this.callback(result);
}
}
// Set imageProvider in LottieView
LottieView({
loop: true,
autoplay: true,
path: $rawfile('common/lottie/data_base64.json'),
controller: this.controller,
imageProvider: new ImageProviderImpl((result: ImageLoadResult) => {
if (result.success) {
console.info('All images loaded successfully');
} else {
console.error('Image load failed: ' + JSON.stringify(result.failedDetails));
}
})
})
Comparison with Lottie
Replacement Description
Lottie requires creating a canvas and manually invoking playback functions, while Lottie-turbo uses the LottieView component for direct loading and playback.

See the figure above for the minimum replacement parts.
Configuration Comparison
| Configuration | Lottie | lottie-turbo |
|---|---|---|
| Rendering | Canvas 2D context | XComponent Surface/Texture (native C++ engine) |
| Initialization | Manual lottie.loadAnimation() |
Declarative LottieView component |
| Control | animationItem return value |
LottieController instance |
| Events | addEventListener on animation item |
LottieListener callback class |
| Cache | No built-in cache | File cache + memory cache |
| Thread Model | Single-threaded | FFRT parallel loading and rendering |
| API | Description | lottie | lottieC |
|---|---|---|---|
| play() | Plays the animation. | Yes | Yes |
| stop() | Stops the animation. | Yes | Yes |
| pause() | Pauses the animation. | Yes | Yes |
| togglePause() | Toggles the animation between playing and paused states. | Yes | Yes |
| destroy() | Destroys the animation. | Yes | Yes |
| goToAndStop() | Seeks to a certain frame or point of time and then stops the animation. | Yes | Yes |
| goToAndPlay() | Seeks to a certain frame or point of time and then starts the animation. | Yes | Yes |
| setSegment() | Sets an animation segment. | Yes | Yes |
| playSegments() | Plays animation segments. | Yes | Yes |
| resetSegments() | Resets the animation. | Yes | Yes |
| setSpeed() | Sets the playback speed. | Yes | Yes |
| setDirection() | Sets the playback direction. | Yes | Yes |
| getDuration() | Obtains the animation duration. | Yes | Yes |
| addEventListener() | Adds an event listener. | Yes | Yes |
| removeEventListener() | Removes an event listener. | Yes | Yes |
| changeColor() | Changes the animation color. | Yes | No. In (layer?: string, Color: number[]), layer indicates the layer, and Color indicates the color. |
| setContentMode() | Sets the fill mode. | Yes | Yes |
| setFrameRate() | Sets the animation frame rate. | Yes | Yes |
| cacheFileClear() | Clear the file cache. | Yes | Yes |
| bindContext2dToCoordinator() | Tracks the dynamic relationship between Lottie animation, CanvasRenderingContext2D, and Canvas. | Yes | Deprecated |
| unbindContext2dFromCoordinator() | Removes the tracking relationship. | Yes | Deprecated |
| setAttachedCanvasHasVisibleArea() | Forcibly corrects the canvas node status associated with context2d. | Yes | Deprecated |
Property Comparison
| Property | Description | lottie | lottieC |
|---|---|---|---|
| animationID | Animation name. | Yes | No (using lottieId) |
| isLoaded | Whether the animation is loaded. | Yes | Yes |
| currentFrame | Current frame. | Yes | Yes |
| currentRawFrame | Number of current frames (floating point). | Yes | Yes |
| firstFrame | Index of the first frame. | Yes | Yes |
| totalFrames | Total frames. | Yes | Yes |
| frameRate | Frame rate (frame/s). | Yes | Yes |
| frameMult | Frame rate (frame/ms). | Yes | Yes |
| playSpeed | Playback speed. | Yes | Yes |
| playDirection | Playback direction. | Yes | Yes |
| playCount | Number of completed playbacks. | Yes | Yes |
| isPaused | Whether to pause the animation. | Yes | Yes |
| isNetLoad | Whether the network is loaded. | Yes | Deprecated |
| autoplay | Autoplay. | Yes | Yes |
| loop | Loop status. | Yes | Yes |
| timeCompleted | Number of frames played in the current animation segment. | Yes | Yes |
| segmentPos | Sequence number of the current animation segment. | Yes | Yes |
| isSubframeEnabled | Whether to update the animation frame rate as frequently as possible. | Yes | Yes |
| segments | Current animation segment. | Yes | Yes |
| packageName | Package name. | Deprecated | Deprecated |
| autoSkip | Whether to skip drawing when the animation is invisible. If this parameter is set to true, the drawing is skipped. | Yes | Yes |
| uri | Network resource loading path. | Yes | No (merged to path) |
| initialSegment | Initial frame range for animation playback. | Yes | Yes |
| animationData | JSON animation data. | Yes | Yes |
| contentMode | Animation fill mode. Fill: Stretch the animation to fill the entire container without maintaining the aspect ratio Cover: Maintain the aspect ratio of the animation, and scale the animation to cover the entire container, which may result in cropping of the animation Top: Maintain the aspect ratio of the animation and align the top of the animation with the top of the container Bottom: Maintain the aspect ratio of the animation, and align the bottom of the animation to the bottom of the container Contain: Maintain the aspect ratio of the animation and scale it to the maximum size suitable for the container (default) AdaptiveHeight: Maintain the aspect ratio of the animation, and adapt the component height according to the component width and animation scale AdaptiveWidth: Maintain the aspect ratio of the animation, and adapt the component width according to the component height and animation scale |
Yes | Yes |
Differences from Upstream rlottie
This library is based on the rlottie rendering engine, with the following key adaptations for OpenHarmony:
| Aspect | Upstream rlottie | lottie-turbo (OpenHarmony) |
|---|---|---|
| Rendering Backend | CPU-only rasterization | XComponent Surface/Texture rendering with GPU acceleration (API16+) |
| Parallelization | Single-threaded | FFRT (Function Flow Runtime) based parallel loading and rendering |
| Platform Integration | Platform-agnostic core | ArkTS wrapper layer with LottieView component and LottieController API |
| Rendering Modes | N/A | Surface mode (default) and Texture mode (API18+) |
| Image Loading | Basic file loading | Supports Base64, URI sandbox paths, and AnimationImageProvider for custom image loading |
| Layer Property APIs | Basic | Extended setLayerProperties API for dynamic modification of text, fill, stroke, transform, shape, gradient, repeater, and image properties |
| Cache System | Basic | File cache and memory cache with configurable size and capacity |
| Event System | Basic callbacks | LottieListener with 13 event callbacks covering full animation lifecycle |
FFRT Thread Model: lottie-turbo uses OpenHarmony's FFRT (Function Flow Runtime) for parallel task scheduling. Animation loading (JSON parsing, image decoding) and frame rendering are dispatched as independent FFRT tasks, enabling multi-core utilization. The native C++ rendering thread communicates with the ArkTS UI thread via threadsafe functions for event callbacks. Developers do not need to manage threads manually, but should avoid calling
destroy()from within listener callbacks to prevent re-entrant deadlocks.
When building from source, the following options in library/build-profile.json5 can be configured:
externalNativeOptions
| Field | Description | Default Value |
|---|---|---|
| path | CMakeLists.txt path | ./src/main/cpp/CMakeLists.txt |
| arguments | CMake build arguments. Default uses RelWithDebInfo for release with debug info. Change to Debug for debug builds. |
-DCMAKE_BUILD_TYPE=RelWithDebInfo |
| cppFlags | C++ compiler flags | "" |
| abiFilters | Target ABIs. Supported: arm64-v8a, x86_64 |
["arm64-v8a","x86_64"] |
nativeLib
| Field | Description | Default Value |
|---|---|---|
| debugSymbol.strip | Whether to strip debug symbols from the native library | true |
| debugSymbol.exclude | Libraries excluded from symbol stripping | [] |
buildOptionSet
The release build option set configures code obfuscation. By default, obfuscation is disabled. To enable it, set enable: true in the ruleOptions section.
About Obfuscation
For code obfuscation, please refer to ArkGuard Principles and Capabilities for Source Code Obfuscation.
To avoid being obfuscated during code obfuscation, add the corresponding exclusion rules to the obfuscation rules configuration file obfuscation-rules.txt:
-keep
./oh_modules/@ohos/lottie-turbo
Remaining Issues
- Animations containing expressions
Directory Structure
/lottie_turbo # Project root directory
├── entry # Sample code
├── library # lottie-turbo library
│ └─ src/main
│ └─ cpp # C++ code
│ └─ ets # ETS code
│ └─ src/main/cpp/types/liblottie-turbo/Index.d.ts # Type declarations
├── README.md # English documentation
├── README_zh.md # Chinese documentation
How to Contribute
If you find any problem when using the project, submit an issue or a PR.
License
This project is licensed under Apache-2.0 License.
Introduction
可用于在移动设备上加载和渲染 Lottie 动画,支持解析 After Effects 导出的 JSON 动画,采用声明式语法创建,具备并行化能力,提供丰富控制功能和事件监听,适配多 API 版本。【此简介由AI生成】
Customize your domain