HarmonyOS鸿蒙Next中关键帧动画keyframeAnimateTo使用

HarmonyOS鸿蒙Next中关键帧动画keyframeAnimateTo使用 效果图:

cke_32944.gif

代码示例:

@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)
  }
}

更多关于HarmonyOS鸿蒙Next中关键帧动画keyframeAnimateTo使用的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中关键帧动画keyframeAnimateTo使用的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,keyframeAnimateTo用于创建关键帧动画。通过定义关键帧,开发者可以精确控制动画在不同时间点的状态。使用步骤包括:

  1. 定义关键帧,设置动画属性;
  2. 调用keyframeAnimateTo,传入关键帧和动画参数;
  3. 启动动画。

例如,实现一个元素从A点移动到B点的动画,可以定义起始和结束关键帧,并设置动画时长和缓动函数。

回到顶部