HarmonyOS 实现圆角矩形的挖空遮罩?

要实现一个黑色半透明的遮罩,然后挖空一个圆角矩形,这部分是全透明的,可以看到原来的圆角矩形的内容。

我能通过CanvasRenderingContext2D的clearRect来挖空一个矩形,但是没看到有自定义形状的API。

Canvas(this.context)
  .width('100%')
  .height('100%')
  .backgroundColor(Color.Transparent)
  .onReady(() =>{
    this.context.fillStyle = '#99000000'
    if (this.isLandscape) {
      this.context.fillRect(0, 0, this.deviceHeight, this.deviceWidth)
    } else {
      this.context.fillRect(0, 0, this.deviceWidth, this.deviceHeight)
    }
    // TODO: 这里是要挖空圆角矩形。但是HarmonyOS没有这个API
    this.context.clearRect(this.area?.globalPosition.x as number, this.area?.globalPosition.y as number, 75, 30);
  })

阅读 502
1 个回答

您参考一下这个demo:

@Entry
@Component
struct CanvasDemo {
  @State message: string = 'Hello World';
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)

  build() {
    Row() {
      Column() {
        Stack() {
          Image($r("app.media.startIcon")).height(300)
          Canvas(this.context)
            .width('100%')
            .height('100%')
            .backgroundColor('#00000000')
            .onReady(() => {
              //圆角弧度
              let radius = 10;
              //左上角坐标x
              let x = 100;
              //左上角坐标y
              let y = 350;
              //矩形宽
              let width = 100;
              //矩形高
              let height = 40;
              this.context.beginPath();
              this.context.moveTo(0, 0)
              this.context.lineTo(0, this.context.height)
              this.context.lineTo(this.context.width, this.context.height)
              this.context.lineTo(this.context.width, 0)
              this.context.lineTo(0, 0)
              this.context.moveTo(x + radius, y);
              this.context.lineTo(x + width - radius, y);
              this.context.arcTo(x + width, y, x + width, y + radius, radius);
              this.context.lineTo(x + width, y + height - radius);
              this.context.arcTo(x + width, y + height, x + width - radius, y + height, radius);
              this.context.lineTo(x + radius, y + height);
              this.context.arcTo(x, y + height, x, y + height - radius, radius);
              this.context.lineTo(x, y + radius);
              this.context.arcTo(x, y, x + radius, y, radius);
              this.context.fillStyle = "#aa000000"
              this.context.fill();
              this.context.closePath();
            })
        }.width('100%')
        .height('100%')
      }
      .width('100%')
    }
    .height('100%')
  }
}