HarmonyOS鸿蒙Next中animation属性动画的基本使用

HarmonyOS鸿蒙Next中animation属性动画的基本使用

@Entry
@Component
struct Page01_animation {
  // 1. 声明相关状态变量
  @State translateY: number = 1
  @State bgColor: ResourceColor = Color.Pink
  @State fontColor: ResourceColor = '#0094ff'
  @State fontWeight: number = 100
  build() {
    Column() {
      Text('C')
        .width(100)
        .height(100)
        .opacity(1)
        // 2.将状态变量设置到相关可动画属性接口
        .fontWeight(this.fontWeight)
        .backgroundColor(this.bgColor)
        .textAlign(TextAlign.Center)
        .translate({ y: this.translateY })
      // 3.通过属性动画接口开启属性动画
      .animation({})
      Button('修改状态变量')
        .onClick(() => {
          // 4. 通过状态变量改变UI界面
          this.bgColor = '#0094ff'
          this.translateY = 100
          this.fontColor = Color.Pink
          this.fontWeight = 900
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.SpaceAround)
  }
}

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

2 回复

在HarmonyOS鸿蒙Next中,animation属性用于实现组件的动画效果。通过animation属性,可以定义动画的名称、持续时间、延迟时间、重复次数等参数。

  1. 定义动画:首先需要在resources目录下的animation文件夹中定义动画资源。例如,定义一个名为rotate_animation.json的旋转动画:

    {
      "animations": [
        {
          "duration": 1000,
          "easing": "linear",
          "from": { "rotate": "0deg" },
          "to": { "rotate": "360deg" }
        }
      ]
    }
    
  2. 应用动画:在组件的样式或属性中,通过animation属性引用定义的动画资源。例如:

    {
      "className": "Text",
      "animation": {
        "name": "rotate_animation",
        "duration": 1000,
        "iterations": "infinite"
      }
    }
    
  3. 动画参数

    • name:动画资源的名称。
    • duration:动画的持续时间,单位为毫秒。
    • delay:动画的延迟时间,单位为毫秒。
    • iterations:动画的重复次数,infinite表示无限重复。
    • easing:动画的缓动函数,如linearease-in等。
  4. 动画事件:可以通过onStartonPauseonResumeonCancelonFinish等事件监听动画的状态变化。

例如:

{
  "className": "Text",
  "animation": {
    "name": "rotate_animation",
    "duration": 1000,
    "iterations": "infinite"
  },
  "onStart": "handleAnimationStart",
  "onFinish": "handleAnimationFinish"
}

在对应的JavaScript或TypeScript文件中,实现handleAnimationStarthandleAnimationFinish方法,以处理动画开始和结束时的逻辑。

通过animation属性,可以轻松实现各种复杂的动画效果,提升用户界面的交互体验。

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


在HarmonyOS鸿蒙Next中,animation属性动画通过Animator类实现。你可以使用AnimatorValueAnimatorObject来定义动画效果。基本步骤包括:

  1. 创建动画对象:使用AnimatorValueAnimatorObject定义动画的起始值和结束值。
  2. 设置动画属性:通过durationdelayrepeatCount等属性配置动画的时长、延迟和重复次数。
  3. 启动动画:调用start()方法启动动画。
  4. 监听动画事件:通过onStartonEnd等回调监听动画的开始、结束等事件。

示例:

const animator = new AnimatorValue(0, 100, 1000); // 从0到100,持续1秒
animator.onStart = () => console.log('动画开始');
animator.onEnd = () => console.log('动画结束');
animator.start();
回到顶部