HarmonyOS中关键帧动画keyframeAnimateTo使用之超速动画案例

30 阅读1分钟

效果图:

示例代码:

@Entry
@Component
struct Index {
  @State myScale: number = 1
  uiContext: UIContext | undefined = undefined;
  @State timeId: number = 0
  @State @Watch("changeSpeed") speed: number = 0
  @State flag: boolean = false

  aboutToAppear() {
    this.uiContext = this.getUIContext?.();
    this.timeId = setInterval(() => {
      this.speed++
    }, 500)
  }

  changeSpeed() {
    if (this.speed == 5) {
      // 触发关键帧动画
      if (!this.flag) this.haha()
      this.flag = !this.flag
    } else if (this.speed == 10) {
      clearInterval(this.timeId)
      this.timeId = setInterval(() => {
        this.speed--
      }, 500)
    } else if (this.speed == 0) {
      clearInterval(this.timeId)
    }
  }

  // 关键帧动画
  haha() {
    if (!this.uiContext) {
      console.info("no uiContext, keyframe failed");
      return;
    }
    this.myScale = 1;
    this.uiContext.keyframeAnimateTo({ iterations: 10 }, [      {        duration: 250,        event: () => {          this.myScale = 1.15;        }      },      {        duration: 250,        event: () => {          this.myScale = 1;        }      }    ])
  }

  build() {
    Column() {
      Column() {
        Column() {}
        .width(90)
        .height(90)
        .borderRadius(45)
        .backgroundColor(Color.Blue)
        .linearGradient({
          direction: GradientDirection.LeftBottom,
          colors: [[this.flag ? 'red' : 'blue', 0.1], [this.flag ? 'FFF18888' : '#ff00aeff', 0.9]]
        })
      }
      .width(100)
      .height(100)
      .borderRadius(50)
      .backgroundColor(Color.White)
      .justifyContent(FlexAlign.Center)
      .scale({ x: this.myScale, y: this.myScale })

      Column() {
        Text(this.speed.toString()).fontWeight(FontWeight.Bold)
        Text('km/h')
      }
      .width(80)
      .height(80)
      .borderRadius(40)
      .backgroundColor(Color.White)
      .justifyContent(FlexAlign.Center)
      .offset({ x: 0, y: -90 })
    }.width('100%').height('100%').backgroundColor(Color.Gray).justifyContent(FlexAlign.Center)
  }
}