【图片】【编缉】图片增加水印(通过组件的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())
相关推荐
卷帘依旧14 小时前
npm包发布和管理流程(AI生成)
前端
小小小小宇15 小时前
前端端内H5调试方法与原理
前端
铁皮饭盒15 小时前
bun 和 pnpm 谁硬? 谁软?
前端·后端
sTone8737515 小时前
Electron 进程架构模型
前端·electron
ZC跨境爬虫15 小时前
跟着 MDN 学CSS day_25:(高级区块效果)
前端·css·html·tensorflow·媒体
Bug-制造者15 小时前
前端流式输出完全指南:原理、实现与工程化实践
前端
暴躁小师兄数据学院16 小时前
【AI大模型应用开发工程师特训笔记】第04讲(第7章):函数与模块
前端·人工智能·python
跟着珅聪学java16 小时前
ECharts subtext(副标题)边距开发教程
前端·javascript·echarts
哈撒Ki16 小时前
快速入门 Electron
前端·面试·electron
还有多久拿退休金16 小时前
LLM应用开发一:给失忆的大模型装上"脑子"——LangChain.js对话记忆从零实战
前端·llm