文档开发者中心
我的

第十九篇:Harmony OS 场景十六:lottie动画

浏览108发布于2025-12-20 04:24北京

一、参考链接

https://ohpm.openharmony.cn/#/cn/detail/@ohos%2Flottie

参考案例:

https://gitee.com/harmonyos-cases/cases/tree/master/CommonAppDevelopment/feature/lottieview

二、示意图:

cke_3854.png

三、相关代码:

cke_3289.png

cke_2831.png

组件中使用:

收起
自动换行
深色代码主题
复制
@Entry
@Component
struct Index {
  build() {
    Column(){
      LottieView()
        .height('100%')
        .width('100%')
    }
  }
}

@Component
export struct LottieView {
  //用来配置CanvasRenderingContext2D对象的参数,包括是否开启抗锯齿,true表明开启抗锯齿。
  private settings: RenderingContextSettings = new RenderingContextSettings(true);
  //用来创建CanvasRenderingContext2D对象,通过在canvas中调用CanvasRenderingContext2D对象来绘制。
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  private politeChicky: string = 'politeChicky'; // 动画名称
  private politeChickyPath:string = "https://assets7.lottiefiles.com/packages/lf20_sF7uci.json" // uri路径,仅支持json格式
  private animateItem: AnimationItem | undefined = undefined; // 初始化loadAnimation接口的返回对象

  aboutToDisappear(): void {
    if (this.animateItem !== undefined) {
      this.animateItem.destroy(this.politeChicky);
    }
  }

  build() {
   Column(){
     Canvas(this.context)
       .width(150)
       .height(150)
       .backgroundColor('#46B1E3')
       .borderRadius(12)
       .onReady(() => {
         // 必须要Canvas组件初始化之后才能执行lottie.loadAnimation方法去加载动画。
         this.initAnimation();
       })
   }
  }

  /**
   * 加载动画
   * @param autoplay 控制动画是否自动播放参数
   */
  initAnimation() {
    //抗锯齿的设置
    this.context.imageSmoothingEnabled = true;
    this.context.imageSmoothingQuality = 'medium';
    // TODO:知识点:lottie.loadAnimation将json数据生成动画
    this.animateItem = lottie.loadAnimation({
      container: this.context,  // 渲染上下文
      renderer: 'canvas',                          // 渲染方式
      loop: true,                                  // 是否循环播放,默认true
      autoplay: true,                              // 是否自动播放,默认true
      name: this.politeChicky,                     // 动画名称
      contentMode: 'Contain',                      // 填充的模式
      frameRate: 30,                               //设置animator的刷帧率为30
      uri: this.politeChickyPath,                  // json路径
    })
  }
}
收藏
1
回复
0
分享
全部评论
暂无评论
暂无评论
写评论
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。
发表
我要写文章
了解社区公约,与您携手共创和谐专业的开发者社区。