实现图片放大功能鸿蒙示例代码

鸿蒙场景化示例代码技术工程师
发布于 2025-3-18 16:26
浏览
0收藏

本文原创发布在华为开发者社区

介绍

本示例构建了一个图片放大案例,主要实现两个功能。

  • 点击放大镜,实现图片放大功能
  • 点击重置图片,将放大后的图片回归原位

实现图片放大功能源码链接

效果预览

实现图片放大功能鸿蒙示例代码-鸿蒙开发者社区

使用说明

  • 打开应用,展示图片、两个按钮。
  • 点击放大镜按钮后,激活放大能力,再次点击图片即可实现图片放大功能。
  • 鼠标按住以及鼠标滚轮操作都可以移动图片的位置,以此来观察图片放大后的局部地方。
  • 点击重置图片按钮,即可将放大的图片恢复为原大小并将图片位置也恢复到原来。

实现思路

  1. 构造readImage()函数,读取图片转化为pixelMap格式。调用getRawFileContentSync函数获取imgUri。
async readImage(imgUri: string, context: Context, decodingOptions?: image.DecodingOptions): Promise<PixelMap | null> {
  const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
  const fileData = resourceMgr.getRawFileContentSync(imgUri)
  const buffer = fileData.buffer.slice(0)
  const imageSourceApi: image.ImageSource = image.createImageSource(buffer)
  let pixmap: image.PixelMap;
  if (decodingOptions) {
    pixmap = await imageSourceApi.createPixelMap(decodingOptions);
  } else {
    pixmap = await imageSourceApi.createPixelMap();
  }
  return pixmap;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  1. 构造resetImg()函数,重置图片状态。
resetImg(): void {
  this.imgScale = 1;
  this.isScaling = true;
  this.imgOffSetX = 0;
  this.imgOffSetY = 0;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  1. 构造TapGesture()函数,实现图片根据手势位置计算放大的功能。
TapGesture()
  .onAction((event: GestureEvent) => {
    if (event && this.isScaling == true) {
      this.imgScale = this.imgScale * Constants.IMAGE_SCALE_3;
      this.imgOffSetX = Constants.IMAGE_WIDTH / 2 - event.fingerList[0].globalX;
      this.imgOffSetY = Constants.IMAGE_HEIGHT / 2 - event.fingerList[0].globalY;
      this.isScaling = false;
    }
  })
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  1. 构造PanGesture()函数,实现图片移动的功能。
PanGesture()
  .onActionStart(() => {
    this.preOffsetX = this.imgOffSetX;
    this.preOffsetY = this.imgOffSetY;
  })
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  1. 设置两个按钮,点击放大镜按钮可以获得放大能力,再次点击图片就可以实现放大功能;点击重置图片按钮,将放大后的图片重置为原大小
Button('放大镜')
  .onClick(() => {
    this.isScaling = true;
  })
Button('重置图片')
  .onClick(()=>{
    this.resetImg();
  })





  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

分类
收藏
回复
举报


回复
    相关推荐