【图片】【编缉】图片增加水印(通过组件的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())
相关推荐
小小龙学IT10 分钟前
Go 语言 reflect 反射包深度解析:从 Type/Value 到三大定律与工业实践
前端·golang
小溪学编程19 分钟前
C语言篇:枚举类型
java·c语言·前端
xingpanvip22 分钟前
星盘接口开发文档:推算星座接口指南
前端·php
Da Da 泓25 分钟前
HTML浅浅入门
前端·html
এ慕ོ冬℘゜27 分钟前
es6基础
前端·javascript·es6
熊猫钓鱼>_>33 分钟前
从2D平铺到3D沉浸:我用HarmonyOS 7端侧AI做了一个全程数据不出设备的空间化私密相册
前端·人工智能·3d·华为·华为云·harmonyos·鸿蒙
m0_738185821 小时前
Flutter 鸿蒙化实战:foundation_fluttify 适配 OpenHarmony,Fluttify 桥接层
flutter·华为·harmonyos·鸿蒙
m0_738185821 小时前
Flutter 鸿蒙化实战:http_proxy 适配 OpenHarmony,HTTP 代理
flutter·http·华为·harmonyos·鸿蒙
m0_738185821 小时前
Flutter 鸿蒙化实战:headset_connection_event 适配 OpenHarmony,耳机插拔监听
flutter·华为·harmonyos·鸿蒙
孔令飞1 小时前
Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中指针引用Go中
前端