目录

文字翻转有延迟

问题现象

文字翻转有延迟,如下图所示。

背景知识

问题定位

@Entry
@Component
struct FlipDemoPage {
  @State flag: boolean = false;
  @State rotateAngle: number = 0;

  build() {
    Column() {
      Button('翻转')
        .onClick(() => {
          this.flag = !this.flag;
          this.rotateAngle = 0;
          this.getUIContext().animateTo({
            duration: 500,
            curve: Curve.EaseInOut,
            onFinish: () => {
              this.rotateAngle = 0;
            }
          }, () => {
            if (this.flag) {
              this.rotateAngle = 180;
            } else {
              this.rotateAngle = -180;
            }
          })
        })
        .margin(50)

      Stack() {
        if (this.flag) {
          Text('0000')
            .fontColor(Color.Blue)
        } else {
          Text('1111')
            .fontColor(Color.Blue)
        }
      }.rotate({
        x: 1,
        y: 0,
        z: 0,
        angle: this.rotateAngle
      })
    }
    .height('100%')
    .width('100%')
  }
}

分析结论

在执行旋转动效实现文字翻转效果时,将动效起始旋转角度设置为0,动效终止旋转角度设置为180或-180,动效执行完成后又将旋转角度设置成0,因此出现文字翻转有延迟的现象。

修改建议

使用组件内转场 (transition)来实现文字翻转动效,在文字显示和消失时增加过渡效果。

@Entry
@Component
struct FlipDemoPage {
  @State flag: boolean = false;

  build() {
    Column() {
      Button('翻转')
        .onClick(() => {
          this.flag = !this.flag;
        })
        .margin(50)

      Stack() {
        if (this.flag) {
          Text('0000')
            .fontColor(Color.Blue)
            .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.ExtremeDeceleration })
              .combine(TransitionEffect.rotate({ x: 1, angle: 180 })))
        } else  {
          Text('1111')
            .fontColor(Color.Blue)
            .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.ExtremeDeceleration })
              .combine(TransitionEffect.rotate({ x: 1, angle: 180 })))
        }
      }
    }
    .height('100%')
    .width('100%')
  }
}