LottieView.ets 2.06 KB
import lottie, { AnimationSegment } from '@ohos/lottie';

@Component
export struct LottieView {
  @Prop name: string = ''
  @Prop path: string = ''
  @Prop lottieWidth?: number = 30
  @Prop lottieHeight?: number = 30
  @Prop autoplay?: boolean = false
  @Prop loop?: boolean = false
  @Prop initialSegment?: AnimationSegment = [0, 120] // 动画起始帧
  @Prop onReady: (animateItem: ESObject) => void // 动画初始化完成事件
  @Prop onComplete?: () => void // 动画完成事件
  private politeChickyController: CanvasRenderingContext2D = new CanvasRenderingContext2D(); // CanvasRenderingContext2D对象
  private animateItem: ESObject = null; // 初始化loadAnimation接口的返回对象

  // 页面隐藏销毁动画
  onPageHide(): void {
    this.animateItem.destroy()

    if (this.onComplete) {
      this.animateItem.removeEventListener('complete', this.onComplete)
    }
  }

  /**
   * 加载动画
   * @param autoplay 控制动画是否自动播放参数
   */
  loadAnimation() {
    // 销毁动画,减少缓存
    if (this.animateItem !== null) {
      this.animateItem.destroy();
      this.animateItem = null;
    }

    this.animateItem = lottie.loadAnimation({
      container: this.politeChickyController,
      renderer: 'canvas',
      loop: this.loop,
      autoplay: this.autoplay,
      name: this.name, // 动画名称
      path: this.path, // hap包内动画资源文件路径,仅支持json格式
      // initialSegment: this.initialSegment
    })
    if (this.initialSegment) {
      this.animateItem.initialSegment = this.initialSegment
    }

    if (this.onComplete) {
      this.animateItem.addEventListener('complete', this.onComplete)
    }

  }

  build() {
    Stack({ alignContent: Alignment.TopStart }) {
      Canvas(this.politeChickyController)
        .width(this.lottieWidth)
        .height(this.lottieHeight)
        .onReady(() => {
          this.loadAnimation();
          if (this.onReady) {
            this.onReady(this.animateItem)
          }
        })
        .onClick(() => {
          this.animateItem.play()
        })
    }
  }
}