【图片】【编缉】图片增加水印(通过组件的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())
相关推荐
UnicornDev4 分钟前
【HarmonyOS 6】底部悬浮导航的迷你栏适配(API23)
华为·harmonyos·arkts·鸿蒙
IT_陈寒9 分钟前
JavaScript的异步地狱,我差点没爬出来
前端·人工智能·后端
光影少年10 分钟前
Webpack打包性能优化方面的经验
前端·webpack·性能优化
Das116 分钟前
通过命令行下载kaggle数据
前端·chrome
@不误正业17 分钟前
OpenHarmony-A2A协议实战-多智能体跨应用协同架构与实现
人工智能·架构·harmonyos·开源鸿蒙
空中海19 分钟前
iOS 静态逆向、IPA 结构与 Mach-O 分析
ios·华为·harmonyos
李李李勃谦20 分钟前
鸿蒙PC文件加密工具实战:AES-256-GCM 加密
华为·harmonyos
maaath25 分钟前
【maaath】Flutter for OpenHarmony打造跨平台便签备忘录应用
flutter·华为·harmonyos
剑神一笑31 分钟前
CSS Animation Timeline 可视化动画编辑器:从关键帧到流畅动画
前端·css·编辑器
Dylan的码园34 分钟前
springBoot与Web后端基础
前端·spring boot·后端