目录

如何设置页面背景的透明度

问题现象

背景知识

解决方案

[h2]场景一

[h2]场景二

可通过给组件添加backgroundColor属性,使用rgba来实现透明背景,具体可参考文档:ResourceColor。

参考demo:

@Entry
@Component
struct ScrollExample {
  scroller: Scroller = new Scroller();
  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  @State alpha: string = '';

  build() {
    Column() {
      Row()
      .width('100%')
        .height(30)
      .backgroundColor(this.alpha);

      Scroll(this.scroller) {
        Column() {
          ForEach(this.arr, (item: string) => {
            Text(item.toString())
              .width('90%')
              .height(150)
              .backgroundColor('#f1f3f5')
              .borderRadius(15)
              .fontSize(16)
              .textAlign(TextAlign.Center)
              .margin({ top: 10 });
          }, (item: string) => item);
        }.width('100%');
      }
      .width('100%')
      // 滚动事件回调,Scroll滚动前触发。
      .onWillScroll((xOffset: number, yOffset: number) => {
        console.info(`xOffset: ${xOffset}, yOffset: ${yOffset}`);
        let offset = this.scroller.currentOffset().yOffset;
        if (offset >= 150) {
          this.alpha = 'rgba(128, 128, 128, 0.80)';
        } else if (offset <= 0) {
          this.alpha = 'rgba(128, 128, 128, 0.60)';
        } else {
          this.alpha = 'rgba(128, 128, 128, 0.30)';
        }
      });
    };
  }
}

效果图如下:

常见FAQ

Q:在元服务中通过setWindowBackgroundColor('#00000000')设置子窗口为透明色为什么不生效?

A:当前的元服务应用内所有子窗都会显示menubar,menubar会产生不透明背景,该效果为当前规格。

Q:编译时报错,提示“Argument of Type 'string|ColorMetrics' is not assignable to parameter of type 'string'”?

A:setWindowBackgroundColor函数从API9开始支持,但ColorMetrics入参类型从API18开始支持,请关注API接口变更情况。

总结