LottieView.ets 2.18 KB
import lottie, { AnimationItem, 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: AnimationItem | null) => void // 动画初始化完成事件
  @Prop onComplete?: () => void // 动画完成事件
  private politeChickyController: CanvasRenderingContext2D =
    new CanvasRenderingContext2D(); // CanvasRenderingContext2D对象
  private animateItem: AnimationItem | null = null; // 初始化loadAnimation接口的返回对象



  /**
   * 加载动画
   * @param autoplay 控制动画是否自动播放参数
   */
  loadAnimation() {

    this.onDestroyAnimation()
    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.segments = this.initialSegment
    }

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

  }

  /**
   * 摧毁动画
   */
  onDestroyAnimation(){
    // 销毁动画,减少缓存
    if (this.animateItem !== null) {
      lottie.destroy(this.name)
      // console.log('lottie', 'onDestroyAnimation')
      this.animateItem = null;
    }

  }


  build() {
    Stack({ alignContent: Alignment.TopStart }) {
      Canvas(this.politeChickyController)
        .width(this.lottieWidth)
        .height(this.lottieHeight)// .backgroundColor(Color.Black)
        .onReady(() => {
          this.loadAnimation();
          if (this.onReady) {
            this.onReady(this.animateItem)
          }
        })
        .onDisAppear(()=>{
          // console.log('lottie', 'onDisAppear')
          this.onDestroyAnimation()
        })
        .onAppear(()=>{
          this.loadAnimation();
        })

    }
  }
}