#鸿蒙通关秘籍#如何利用HarmonyOS Next的animateTo函数实现组件自动触发动画?

HarmonyOS
2024-11-29 15:27:34
503浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
NoSQL晨光初照

在HarmonyOS Next中,利用animateTo函数的特点,可以在组件的onAppear回调中设置动画,使组件一加载就自动触发动画,这种方式尤其适合于创建持续的视觉效果,例如水波纹。关键在于animateTo函数的事件绑定位置和动画的无限循环播放设置:

@Entry
@Component
struct Demo {
  @State scaleList: number[] = []
  @State opacityList: number[] = [] 
  private cloneScaleList: number[] = [] 
  private cloneOpacityList: number[] = [] 
  private scaleRatio:number=0.7 

  aboutToAppear(): void {
    this.scaleList = new Array(3).fill('').map((item: string, index: number) => 1 + index * this.scaleRatio)
    this.opacityList = new Array(3).fill('').map((item: string, index: number) => (3 - index)/10 )
    this.cloneScaleList = this.scaleList.slice()
    this.cloneOpacityList = this.opacityList.slice()
  }

  build() {
    Column({ space: 50 }) {
      Stack() {
        ForEach(this.scaleList, (item: number, index: number) => {
          Column() {
          }
          .width(50)
          .height(50)
          .borderRadius(25)
          .backgroundColor('#1463F4')
          .opacity(this.opacityList[index])
          .scale({ x: this.scaleList[index], y: this.scaleList[index] })
          .onAppear(() => {
            animateTo({ duration: 1200, iterations: -1 }, () => {
              this.scaleList[index] = this.cloneScaleList[index] + this.scaleRatio
              this.opacityList[index] = this.cloneOpacityList[index] -  0.1
            })
          })
        }, (item: number, index: number) => index.toString())

        Image($r('app.media.app_icon')).width(50).borderRadius(25)
      }
    }.height('100%').width('100%').justifyContent(FlexAlign.Center).alignItems(HorizontalAlign.Center)
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
分享
微博
QQ
微信
回复
2024-11-29 17:20:47
相关问题