导入lottie动画库
导入命令
ohpm install @ohos/lottie
导入成功后可在entry目录下的oh-package.json5文件下查看lottie版本,如:
"dependencies": {
"@ohos/lottie": "^2.0.11"
},
使用lottie
import { webview } from '@kit.ArkWeb'
import lottie, { AnimationItem } from '@ohos/lottie';
@Entry
@Component
export struct Detail {
@State isCanvasVisible: Visibility = Visibility.Visible;
private animateItem: AnimationItem | null = null;
private animationName: string = "haha"
private mainRenderingSettings: RenderingContextSettings = new RenderingContextSettings(true) //开启抗锯齿
private mainCanvasRenderingContext: CanvasRenderingContext2D =
new CanvasRenderingContext2D(this.mainRenderingSettings) //创建2D
aboutToDisappear(): void {
lottie.destroy()
}
aboutToAppear(): void {
console.log("testTag", "aboutToAppear");
this.loadAnimation()
}
onPageHide(): void {
lottie.pause()
}
//加载动画
loadAnimation() {
console.log('canvas onAppear');
this.animateItem?.destroy(this.animationName); //加载动画前先销毁之前加载的动画
this.animateItem = lottie.loadAnimation({
container: this.mainCanvasRenderingContext, // 渲染上下文
renderer: 'canvas', // 渲染方式
loop: true, // 是否循环播放,默认true
autoplay: true, // 是否自动播放,默认true
name: this.animationName, // 动画名称
contentMode: 'Contain', // 支持填充模式:Fill, Top, Cover, Bottom, Contain 默认模式是:Contain
path: "common/lottie/lottie_animation.json", // lottie动画文件的路径
})
}
//webController: webview.WebviewController = new webview.WebviewController()
build() {
Column() {
//关联画布
Canvas(this.mainCanvasRenderingContext)
.id("canvas")
.width('100%')
.height(500)
.onReady(() => {
this.mainCanvasRenderingContext.imageSmoothingEnabled = true;
this.mainCanvasRenderingContext.imageSmoothingQuality = 'medium'
this.animateItem?.resize();
})
.onDisAppear(() => {
lottie.destroy(this.animationName);
})
.visibility(this.isCanvasVisible)
//Web({src:'http://www.huawei.com/cn',controller:this.webController})
Text("暂停")
.fontSize("20fp")
.onClick(() => {
lottie.pause()
}).TextFont()
Text("播放")
.fontSize(20)
.onClick(() => {
lottie.play()
}).TextFont()
}
}
}
@Extend(Text)
function TextFont() {
.fontSize(20)
.backgroundColor(Color.Orange)
.fontColor(Color.Red)
.padding(10)
.margin({ top: 20 })
.borderRadius(5)
.width(100)
.textAlign(TextAlign.Center)
}
以上就是lottie的基本使用方式,记录一下。
openHarmony三方库,里面有很多三方库,也包含使用说明。