目录

如何解决AttributeModifier封装scale动画问题

问题现象

效果预览

背景知识

AttributeModifier支持自定义class实现动态设置组件的属性,但不支持封装animation属性。组件的布局类属性(如scale、rotate等)变化时的动画效果,无法用AttributeModifier封装。

问题定位

分析结论

  1. AttributeModifier不支持封装组件的scale属性,所以无法实现动画效果。
  2. AttributeModifier的onAppear、onDisAppear只作用于自身,不会跟随被绑定的组件生命周期。

修改建议

不用AttributeModifier封装,直接使用class封装startShowDialog、exitShowDialog方法,在组件尾部直接调用scale方法,在startShowDialog中修改scaleDialog后,变化同步至scale,实现动画效果。通过export关键字可将封装的class导出,即可在别的文件中调用。

// 动画封装类
export class AnimateTest {
  @Track scaleDialog: number;

  constructor(num: number) {
    this.scaleDialog = num;
  }

  // 缩小按钮的帧动画
  startAnimate(context: UIContext) {
    context.keyframeAnimateTo({ iterations: 1 }, [
      {
        duration: 500,
        event: () => {
          this.scaleDialog = 0.5;
        }
      }
    ]);
  }
}

@Entry
@Component
struct AttributeModifierAnimateDemo {
  @State message: string = 'Button';
  @State animate: AnimateTest = new AnimateTest(3);

  build() {
    Column() {
      Button(this.message)
        .backgroundColor('#0A59F7')
        .width(70)
        .height(100)
        .scale({
          // 监听动画类中scaleDialog变化来缩放
          x: this.animate.scaleDialog,
          y: this.animate.scaleDialog,
          centerX: '50%',
          centerY: '50%'
        })
        .onClick(() => {
          this.message = 'Button2';
          let context = this.getUIContext();
          // 开始动画
          this.animate.startAnimate(context);
        });
    }.height('100%').width('100%').justifyContent(FlexAlign.Center);
  }
}