0
点赞
收藏
分享

微信扫一扫

Harmonyos5应用开发实战——图像裁剪与精修功能实现(part1)

文章概要

本文聚焦于HarmonyOS Next平台上图像裁剪与精修功能的开发实践。详细介绍了如何在应用中实现图像的加载、裁剪、旋转、滤镜应用以及水印添加等核心功能,为开发者在HarmonyOS Next环境下进行图像相关应用开发提供了实用的参考。

核心功能及代码实现
1. 页面初始化与图像加载

在页面即将显示时,进行窗口隐私模式设置、获取导航参数并加载图像。代码如下:

async aboutToAppear(): Promise<void> {
  window.getLastWindow(getContext(this)).then((windowStage: window.Window) => {
    windowStage.setWindowPrivacyMode(true);
  });
  this.filters = filtersData;
  let navParams: RouterParams[] = this.pageRouter.getParamByName(RouteMap.PIC_CROP) as RouterParams[];
  this.fromPath = navParams[0].from;
  this.loadImage(navParams[0].imageUri);
}

loadImage(uri: string) {
  let imageBuffer = ImageUtils.getBufferByUri(uri);
  let imageSource: image.ImageSource = image.createImageSource(imageBuffer);
  imageSource.getImageInfo((err, value) => {
    this.canvasSize = this.getComponentSize(ImageConstants.WATERMARK_BOX_ID);
    if (err) {
      return;
    }
    this.imageHeight = Math.round(value.size.height * 1);
    this.imageWidth = Math.round(value.size.width * 1);
    let desiredSize: image.Size = {
      height: this.imageHeight,
      width: this.imageWidth
    };
    let opts: image.DecodingOptions = {
      editable: true,
      desiredSize
    };
    imageSource.createPixelMap(opts, async (err, pixelMap) => {
      if (err) {
        return;
      }
      let widthScale = this.canvasSize.width / this.imageWidth;
      let heightScale = this.canvasSize.height / this.imageHeight;
      this.imageScale = Math.min(widthScale, heightScale);
      this.imageHeightTrans = this.imageHeight * this.imageScale;
      this.imageWidthTrans = this.imageWidth * this.imageScale;
      this.waterMarkContext.transform(this.imageScale, 0, 0, this.imageScale, 0, 0);
      this.pixelMap = ImageUtils.clonePixelMap(pixelMap);
      this.rawPixelMap = ImageUtils.clonePixelMap(pixelMap);
      if (this.fromPath === 'edit') {
        this.initFilterImages();
      }
      this.drawImage();
    });
  });
}

2. 裁剪与旋转操作

提供了裁剪和旋转图像的功能,通过点击相应按钮触发操作。代码如下:

@Builder
CropOperationBar() {
  Column() {
    // ...
    Row() {
      this.CustomButton($r('app.media.reset'), '重置', (event: ClickEvent) => {
        this.pixelMap = ImageUtils.clonePixelMap(this.rawPixelMap as PixelMap);
        this.drawImage();
      });
      this.CustomButton($r('app.media.rotate'), '旋转', async (event: ClickEvent) => {
        await rotateImage(this.pixelMap, CommonConstants.CLOCK_WISE);
        this.drawImage();
      });
    }
    // ...
  }
}

async handleCropImage() {
  const cropWidth = Math.floor(this.imageHeight * 0.75);
  const cropHeight = this.imageHeight;
  await cropImage(this.pixelMap, Math.floor((this.imageWidth - cropWidth) / 2), 0, cropWidth, cropHeight);
  this.imageWidth = cropWidth;
  this.drawImage();
  return;
}

举报

相关推荐

0 条评论