HarmonyOS 怎么做到一个组件全部是红色,中间挖空是透明的

HarmonyOS
2024-12-24 16:53:07
633浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Heiang

1、先屏幕填充半透明背景fillRect。

2、居中矩形将背景擦除掉clearRect。

import display from '@ohos.display';
@Entry
@Component
struct CustomPage {
  //用来配置CanvasRenderingContext2D对象的参数,包括是否开启抗锯齿,true表明开启抗锯齿。
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  //用来创建CanvasRenderingContext2D对象,通过在canvas中调用CanvasRenderingContext2D对象来绘制。
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private pointX: number = 30;
  private pointY: number = 150;
  private mScanWidth: number = 300;
  private mScreenWidth: number = 1080;
  private mScreenHeight: number = 1920;
  @State mIsInit: boolean = false;
  onPageShow(): void {//需在真机运行
    console.info('onPageShow');
    // 获取屏幕参数
    let defaultDisplay = display.getDefaultDisplaySync();
    this.mScreenWidth = px2vp(defaultDisplay.width);
    this.mScreenHeight = px2vp(defaultDisplay.height);
    // 计算扫描框边长
    this.mScanWidth = this.mScreenWidth * 0.8;
    // 计算扫描框左上角位置
    this.pointX = (this.mScreenWidth - this.mScanWidth) / 2;
    this.pointY = (this.mScreenHeight - this.mScanWidth) / 2;
    console.info(`${this.pointX}, pointY: ${this.pointY}, mScanWidth: ${this.mScanWidth}`);
    this.mIsInit = true;
  }
  build() {
    Stack() {
      Text('这里是底色').fontSize(180).width('100%').height('100%')
      if (this.mIsInit) { // 数据初始化完后才需要显示
        Canvas(this.context)
          .width('100%')
          .height('100%')
          .onReady(() => {
            this.context.fillStyle = '#33000000';
            this.context.fillRect(0, 0, this.mScreenWidth, this.mScreenHeight);
            this.context.clearRect(this.pointX, this.pointY, this.mScanWidth, this.mScanWidth);
          })
      }
    }.width('100%')
    .height('100%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
分享
微博
QQ
微信
回复
2024-12-24 19:11:49


相关问题
怎么判断一个类型stirng
1615浏览 • 1回复 待解决
如何新开一个透明页面?
778浏览 • 1回复 待解决