【图片】【编缉】图片增加水印(通过组件的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())
相关推荐
gustt3 小时前
JS 变量那些坑:从 var 到 let/const 的终极解密
前端·javascript
出师未捷的小白3 小时前
[NestJS] 手摸手~工作队列模式的邮件模块解析以及grpc调用
前端·后端
Z_B_L4 小时前
问题记录--elementui中el-form初始化表单resetFields()方法使用时出现的问题
前端·javascript·vue.js·elementui·1024程序员节
袁煦丞4 小时前
PandaWiki开源知识库系统破解内网限制:cpolar内网穿透实验室第616个成功挑战
前端·程序员·远程工作
golang学习记4 小时前
Next.js MCP Server 实战指南:让 AI 编程助手真正“懂”你的应用
前端
柳鲲鹏4 小时前
多种方法:OpenCV中修改像素RGB值
前端·javascript·opencv·1024程序员节
susu10830189114 小时前
chrome浏览器设置为手机模式
前端·chrome
IT_陈寒5 小时前
SpringBoot 3.2 实战:这5个新特性让你的开发效率提升50%!
前端·人工智能·后端