目录

如何实现组件向上移动时被幕布遮挡的效果

问题现象

组件初始在幕布下方,如何实现点击后该组件缓慢运动直至被幕布组件完全遮挡的效果?

效果预览

背景知识

解决方案

  1. 将幕布组件的zIndex值设置为100,目标组件的zIndex值设置为50。
  2. 为目标组件添加onClick点击事件,在该事件中通过getUIContext方法获取UIContext实例对象,并调用animateTo方法,将组件的纵坐标设置为230,实现目标组件向上平移的效果。
  3. 由于幕布组件的zIndex值更高,因此运动组件在接触到幕布组件的下缘时就会慢慢消失,产生被幕布遮罩的视觉效果。

完整示例参考如下:

@Entry
@Component
struct CurtainCoverageDemo {
  @State y: number = 400;

  build() {
    Column() {
      // 模拟幕布
      Column() {
        Text('幕布组件')
          .textAlign(TextAlign.Center)
          .align(Alignment.Center);
      }
      .justifyContent(FlexAlign.Center)

      .size({ width: '100%', height: 100 })
      .position({
        top: 250
      })
      .zIndex(100)
      .backgroundColor('#f0f2f4');

      // 被遮罩的运动组件
      Row() {
        Text()
          .size({ width: 60, height: 60 })
          .fontSize(12)
          .fontColor('#81D3F8')
          .borderRadius(40)
          .backgroundColor('#1d52c2')
          .zIndex(50);
      }
      .size({ width: 60, height: 60 })
      .margin({ top: 50 })
      .translate({ y: this.y }) // 向上平移
      .onClick(() => {
        setTimeout(() => {
          this.getUIContext().animateTo({ duration: 1000 }, () => {
            this.y = 230;
          });
        }, 1000);
      });
    }
    .width('100%')
    .height('100%')
    .backgroundColor(Color.White);
  }
}

总结

zIndex可设置组件的堆叠顺序,zIndex值大的组件会覆盖在zIndex值小的组件上方。