用户可用于在 OpenHarmony 应用中加载和渲染 Lottie 动画。该项目能解析 After Effects 导出的 JSON 动画,支持声明式语法创建,具备并行化能力,提供播放控制、事件监听等核心功能。【此简介由AI生成】
Access rate limit exceeded. Please log in to continue.
lottie-turbo
This project is developed based on lottie-turbo.
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 ohpm Packages.
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:
- DevEco Studio: 5.0.4 Release (5.0.11.100), SDK: API16 (5.0.0.150), ROM: 5.1.0.120.
Permission Requirements
None.
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(); // Pause 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.controller1.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 " + eventName + "\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 5000 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. |
(1) Configuring Listener When Creating LottieView
// Configure the listener.
private listener: LottieListener = new LottieListener({
onDrawFrame: () => {
onsole.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[];
- 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": "- DCCMAKE_SUILD_TYPE=Release" 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
Currently, only dynamic setting of text content and color for text layers is supported.
export interface LayerProperties {
// Text layer properties
textLayerProperties?: TextLayerProperties[];
}
export interface TextLayerProperties {
// Text content
text?: string;
// Fill color
fillColor?: TextColorConfig;
// Fill opacity, range [0 - 100]
fillOpacity?: number;
// Stroke color
strokeColor?: TextColorConfig;
// Stroke opacity, range [0 - 100]
strokeOpacity?: number;
}
export interface TextColorConfig {
// Red component, range [0 - 1]
r: number;
// Green component, range [0 - 1]
g: number;
// Blue component, range [0 - 1]
b: number;
}
(1) Non-key Frame
// Note: The first parameter represents the layer name, and the second parameter is the dynamically set graphic properties.
// Currently, supported properties include text content, color, and opacity for text layers.
// Color values range from 0–1, and opacity ranges from 0–100.
// Return values: 0 - success, 1 - invalid parameter, 2 - animation not loaded, 3 - property parsing failed, 4 - layer not found.
// Modify the text content of a text layer
let properties: LayerProperties = { textLayerProperties: [{ text: 'New Text' }] };
let result: number = this.controller.setLayerProperties("LayerName", properties);
// Modify the fill color of text (without opacity)
let fillColor: TextColorConfig = { r: 0.38, g: 0.59, b: 0.0 };
let properties: LayerProperties = { textLayerProperties: [{ fillColor: fillColor }] };
let result: number = this.controller.setLayerProperties("LayerName", properties);
// Modify the fill color of text (with opacity)
let fillColor: TextColorConfig = { r: 0.38, g: 0.59, b: 0.0 };
let properties: LayerProperties = { textLayerProperties: [{ fillColor: fillColor, fillOpacity: 50 }] };
let result: number = this.controller.setLayerProperties("LayerName", properties);
// Modify text content, fill color (with opacity), and stroke color (with opacity)
let fillColor: TextColorConfig = { r: 0.38, g: 0.59, b: 0.0 };
let strokeColor: TextColorConfig = { r: 0.93, g: 0.17, b: 0.55 };
let properties: LayerProperties = {
textLayerProperties: [{
text: 'New Text',
fillColor: fillColor,
fillOpacity: 100,
strokeColor: strokeColor,
strokeOpacity: 80
}]
};
let result: number = this.controller.setLayerProperties("LayerName", properties);
(2) Key Frame
// Note: The first parameter represents the layer name, and the second parameter is the dynamically set graphic properties.
// Currently, only text layer properties are supported. These are provided as an array,
// where each element corresponds to a keyframe and contains the properties to be dynamically set.
// Currently supported properties include text content, color, and opacity.
// Color values range from 0–1, and opacity ranges from 0–100.
// Return values: 0 - success, 1 - invalid parameter, 2 - animation not loaded, 3 - property parsing failed, 4 - layer not found.
// Modify the text of the first keyframe, and the text and fill color (without opacity) of the third keyframe
let frame1: TextLayerProperties = { text: 'Frame 1' };
let frame3: TextLayerProperties = { text: 'Frame 3', fillColor: { r: 1.0, g: 0.0, b: 0.0 } };
let properties: LayerProperties = { textLayerProperties: [frame1, {}, frame3] };
let result: number = this.controller.setLayerProperties("LayerName", properties);
// Modify the text of the first keyframe, and the text and fill color (with opacity) of the third keyframe
let frame1: TextLayerProperties = { text: 'Frame 1' };
let frame3: TextLayerProperties = {
text: 'Frame 3',
fillColor: { r: 1.0, g: 0.0, b: 0.0 },
fillOpacity: 100
};
let properties: LayerProperties = { textLayerProperties: [frame1, {}, frame3] };
let result: number = this.controller.setLayerProperties("LayerName", properties);
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 |
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 |
Comparison with LottieArkTS
Replacement Description
LottieArkTS 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
Method Comparison
| API | Description | lottieArkTS | 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 | lottieArkts | 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 |
About Obfuscation
For code obfuscation, please refer to Code Obfuscation Overview.
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
│ └─ 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
用户可用于在 OpenHarmony 应用中加载和渲染 Lottie 动画。该项目能解析 After Effects 导出的 JSON 动画,支持声明式语法创建,具备并行化能力,提供播放控制、事件监听等核心功能。【此简介由AI生成】
Customize your domain