【图片】【编缉】图片增加水印(通过组件的Overlay方法增加水印)

对图片增加水印经常在分享,版权保护等场景使用,在鸿蒙系统中提供了多种方,本篇介绍通过组件的Overlay方法增加水印的方法,是对组件进行的水印操作。代码如下,主要分为两步

第一步,实现增加水印的组件,该组件实现水印内容的绘制

kotlin 复制代码
@Component
export struct Watermark {
  private settings: RenderingContextSettings = new RenderingContextSettings(true);
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  @Prop watermarkWidth: number = 120;
  @Prop watermarkHeight: number = 120;
  @Prop watermarkText: string = "水印";
  @Prop rotationAngle: number = -30;
  @Prop fillColor: string | number | CanvasGradient | CanvasPattern = '#10000000';
  @Prop font: string = '16vp';

  draw() {
    this.context.fillStyle = this.fillColor;
    this.context.font = this.font;
    const colCount = Math.ceil(this.context.width / this.watermarkWidth);
    const rowCount = Math.ceil(this.context.height / this.watermarkHeight);
    for (let col = 0; col <= colCount; col++) {
      let row = 0;
      for (; row <= rowCount; row++) {
        const angle = this.rotationAngle * Math.PI / 180;
        this.context.rotate(angle);
        const positionX = this.rotationAngle > 0 ? this.watermarkHeight * Math.tan(angle) : 0;
        const positionY = this.rotationAngle > 0 ? 0 : this.watermarkWidth * Math.tan(-angle);
        this.context.fillText(this.watermarkText, positionX, positionY);
        this.context.rotate(-angle);
        this.context.translate(0, this.watermarkHeight);
      }
      this.context.translate(0, -this.watermarkHeight * row);
      this.context.translate(this.watermarkWidth, 0);
    }
  }

  build() {
    Canvas(this.context)
      .width('100%')
      .height('100%')
      .hitTestBehavior(HitTestMode.Transparent)
      .onReady(() => this.draw())
  }
}

第二步,对组件增加水印Builder,在调用的页面类实现

scss 复制代码
struct OverlayWatermarkPage {
  // 开始Builder
  @Builder
  watermarkBuilder() {
    Column() {
      Watermark()
    }
  }
  // 结束Builder
}

使用代码

scss 复制代码
Image($r('app.media.image'))
  .width(110)
  .height(88)
  .overlay(this.watermarkBuilder())
相关推荐
夏文强18 小时前
HarmonyOS开发-ArkWeb开发指导
华为·harmonyos
猪猪拆迁队19 小时前
前端图形引擎架构设计:双引擎架构设计
前端·后端·架构
宋辰月19 小时前
学习react第三天
前端·学习·react.js
bug总结19 小时前
更新原生小程序封装(新增缓存订阅)完美解决
前端·缓存·小程序
5335ld20 小时前
后端给的post 方法但是要求传表单数据格式(没有{})
开发语言·前端·javascript·vue.js·ecmascript
二川bro20 小时前
第33节:程序化生成与无限地形算法
前端·算法·3d·threejs
QDKuz20 小时前
掌握Vue2转Vue3, Options API 转 Composition API
前端·javascript·vue.js
Georgewu20 小时前
【HarmonyOS 6】SpeechKit中的朗读控件,初始化前不进行窗口舞台的设置,也不会报错,与文档描述不符。
harmonyos
老前端的功夫20 小时前
前端Echarts性能优化:从卡顿到流畅的百万级数据可视化
前端·javascript
进击的野人20 小时前
深入解析localStorage:前端数据持久化的核心技术
前端·javascript