推荐使用lottie-turbo:声明式调用更加简洁
//1.方案一:
@ohos/lottie-turbo-OpenHarmony三方库中心仓
注意:路径资源在工程entry/src/main/resources/rawfile下
步骤一:下载安装
ohpm install @ohos/lottie-turbo
步骤二:
import { LottieController, LottieView } from '@ohos/lottie-turbo';
@Entry
@Component
struct LottiePage {
private controller: LottieController = new LottieController();
build() {
Column() {
LottieView({
lottieId: "lottie1", //动画id,需要保证唯一性
loop: true, //是否循环播放,非必须,默认为true
autoplay: true, //是否自动播放,非必须,默认为true
autoSkip: true, //不可见时是否自动跳过渲染,非必须,默认为true
path: $rawfile('xq.json'), //通过rawfie文件播放
// path: "https://cdn.lottielab.com/l/7Zgk9iuQxmZ3tD.json", //通过uri播放
// 通过动画json的字符串播放(string类型),该属性优先级> 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动画控制器
})
.width(160)
.height(160)
// .backgroundColor(Color.Gray)
.onClick(() => {
this.controller.togglePause(); //控制动画播放暂停
})
}
.height('100%')
.width('100%')
}
}
//2.方案二:
注意:path 参数:只支持加载entry/src/main/ets 文件夹下的相对路径,不支持跨包查找文件。
@ohos/lottie-OpenHarmony三方库中心仓
步骤一:
下载安装
ohpm install @ohos/lottie
步骤二:
import lottie, { AnimationItem } from "@ohos/lottie";
@Entry
@Component
export struct LottiePage02 {
name = "xq"
private animateItem: AnimationItem | null = null;
private renderingSettings: RenderingContextSettings = new RenderingContextSettings(true)
private canvasRenderingContext: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.renderingSettings)
private animateItem2: AnimationItem | null = null;
aboutToAppear(): void {
console.info('aboutToAppear');
lottie.destroy('aboutToAppear')
this.animateItem2 = lottie.loadAnimation({
container: this.canvasRenderingContext,
renderer: 'canvas', // canvas 渲染模式
loop: true,
autoplay: true,
name: this.name,
contentMode: 'Contain',
path: "pages/common/lottie/" + this.name + ".json",
})
}
build() {
Column() {
Stack() {
Canvas(this.canvasRenderingContext)
.width('120')
.height('120')
//.backgroundColor(Color.Gray)
.onReady(() => {
this.animateItem2?.resize();
})
.onDisAppear(() => {
// 组件移除时,可销毁动画资源
lottie.destroy(this.name);
})
}
}
}
}