智能客服
你问我答,随时在线为你解决问题
在全局自定义Builder函数中,通过修改组件的属性,如何实现动画效果?问题代码示例参考如下:
@Builder function bottomViewBuilder() { Column() { Image($r('app.media.start_branding_light_icon')) .width(150) } .padding({ bottom: AppStorage.get('bottomRectHeight') as number }) .justifyContent(FlexAlign.End) .backgroundColor($r('app.color.background_color_level2')) .width(windowWidth) .height(windowHeight - adHeight) .animation({ duration: 1000, curve: Curve.Linear, playMode: PlayMode.Normal }) .onAppear(() => { }) }
以上代码中windowWidth、windowHeight、adHeight为全局变量,当全局变量修改时,无法触发动画效果。
@Builder function bottomViewBuilderOne(simple: AnimatesOne) { Column() { Image($r('app.media.startIcon')) .width(150); } .padding({ bottom: AppStorage.get('bottomRectHeight') as number }) .justifyContent(FlexAlign.End) .width(simple.windowWidth) .height(simple.windowHeight - simple.adHeight) .onAppear(() => { }); } // 动画属性只支持状态变量的修改,同时由于Builder的传参限制,建议封装为一个可深度观测的类 class AnimatesOne { @Track windowWidth: number = 100; @Track windowHeight: number = 100; @Track adHeight: number = 0; } @Entry @Component struct OptionOne { @State simple: AnimatesOne = new AnimatesOne(); build() { Column() { Text('开始动画') .onClick(() => { this.getUIContext()?.animateTo({ duration: 2000, curve: Curve.Linear, iterations: -1, playMode: PlayMode.Normal, onFinish: () => { console.info('play end'); } }, () => { this.simple.windowWidth = 200; this.simple.adHeight = 50; }); }); bottomViewBuilderOne(this.simple); }; } }
@Builder function bottomViewBuilderTwo(simple: AnimatesTwo) { Column() { Image($r('app.media.startIcon')) .width(150); } .padding({ bottom: AppStorage.get('bottomRectHeight') as number }) .justifyContent(FlexAlign.End) .width(simple.windowWidth) .height(simple.windowHeight - simple.adHeight) .animation({ duration: 3000, iterations: -1, curve: Curve.Linear, playMode: PlayMode.Normal }) .onAppear(() => { }); } class AnimatesTwo { @Track windowWidth: number = 100; @Track windowHeight: number = 100; @Track adHeight: number = 0; } @Entry @Component struct OptionTwo { @State simple: AnimatesTwo = new AnimatesTwo(); build() { Column() { Text('开始动画') .onClick(() => { this.simple.windowWidth = 200; this.simple.adHeight = 50; }); bottomViewBuilderTwo(this.simple); }; } }
效果预览:

由于全局自定义函数的Builder的父容器Column组件没有设置宽高限制,导致Column组件自适应子组件大小,所以Text组件也跟随移动。