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

HarmonyOS
11h前
浏览
收藏 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)
  }
}
分享
微博
QQ
微信
回复
10h前
相关问题