本文原创发布在华为开发者社区

介绍

本示例使用组件默认属性overlay实现组件级水印效果。

实现全局水印源码链接

效果预览

请添加链接描述

使用说明

  1. 水印效果,只需要在组件加上默认属性overlay即可
  2. 每一个页面都加上,即可实现全局水印

实现思路

  1. 通过canvas绘制水印
  2. 在用到的页面,在组件加上默认属性overlay
    核心代码如下:

Canvas(this.context)
  .width('100%')
  .height('100%')
  .hitTestBehavior(HitTestMode.Transparent)
  .onReady(() => {
    // TODO:知识点:通过canvas绘制水印
    this.context.fillStyle = '#10000000';
    this.context.font = '16vp';
    this.context.textAlign = 'center';
    this.context.textBaseline = 'middle';
    for (let i = 0; i < this.context.width / 120; i++) {
      this.context.translate(120, 0);
      let j = 0;
      for (; j < this.context.height / 120; j++) {
        this.context.rotate(-Math.PI / 180 * 30);
        this.context.fillText('水印水印', -60, -60);
        this.context.rotate(Math.PI / 180 * 30);
        this.context.translate(0, 120);
      }
      this.context.translate(0, -120 * j);
    }
  })
}

需要使用的页添加overlay属性


RelativeContainer() {
  Text(this.message)
    .id('HelloWorld')
    .fontSize(50)
    .fontWeight(FontWeight.Bold)
    .alignRules({
      center: { anchor: '__container__', align: VerticalAlign.Center },
      middle: { anchor: '__container__', align: HorizontalAlign.Center }
    })
}
.overlay(createWaterMarkView())  // 水印效果,只需要在组件加上默认属性overlay即可
// 每一个页面都加上,即可实现全局水印

鸿蒙场景化代码
1 声望0 粉丝