鸿蒙Next如何实现循环旋转动画

在鸿蒙Next中,如何实现一个View的循环旋转动画?我想让一个图片或控件持续旋转,类似加载动画的效果,但不太清楚具体该用什么组件和API来实现。能否提供一个简单的代码示例,说明如何设置旋转速度、方向和循环次数?最好能同时讲解一下动画的启动和停止控制方法。

2 回复

鸿蒙Next实现循环旋转动画?简单!用animateTorotate属性,设置iterationCount: -1(无限循环),再加个easing曲线,搞定!代码比老板画的饼还圆润~

更多关于鸿蒙Next如何实现循环旋转动画的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next(HarmonyOS NEXT)中,可以通过ArkUI的animateTo方法或属性动画实现循环旋转动画。以下是两种实现方式:

1. 使用animateTo方法(推荐)

import { animateTo } from '@kit.ArkUI';

@Entry
@Component
struct RotateExample {
  @State angle: number = 0;

  build() {
    Column() {
      Image($r('app.media.icon'))
        .width(100)
        .height(100)
        .rotate({ angle: this.angle })
        .onClick(() => {
          this.startRotation();
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }

  startRotation() {
    // 每次旋转360度,持续2秒,无限循环
    animateTo({
      duration: 2000,
      iterations: -1, // -1表示无限循环
      onFinish: () => {
        console.log('Animation completed');
      }
    }, () => {
      this.angle += 360;
    })
  }
}

2. 使用属性动画

@Entry
@Component
struct RotateExample {
  @State angle: number = 0;

  aboutToAppear() {
    // 组件出现时开始动画
    this.startRotation();
  }

  build() {
    Column() {
      Image($r('app.media.icon'))
        .width(100)
        .height(100)
        .rotate({ angle: this.angle })
        .animation({
          duration: 2000,
          iterations: -1,
          curve: Curve.Linear
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }

  startRotation() {
    setInterval(() => {
      this.angle = (this.angle + 360) % 360;
    }, 2000);
  }
}

关键参数说明:

  • duration:动画持续时间(毫秒)
  • iterations: -1:无限循环
  • curve: Curve.Linear:匀速运动曲线
  • 使用rotate修饰符设置旋转角度

第一种方法更简洁,推荐使用animateTo实现循环旋转动画。

回到顶部