HarmonyOS 如何进行图片裁剪

项目中会使用到拍照或者从相册选择功能选中图片后进行裁剪,选取图片的其中某一区域进行设置头像功能,具体需求如下:

1、不论是拍照还是从相册选择,回调成功后会跳转至一个新的页面

2、页面展示所拍的图片,展示规则:竖图则竖着展示,横图则横着展示,从相册选择同样 竖图则竖着展示,横图则横着展示

3、图片上浮一个9宫格,拖动中间细线整体托动9宫格。拉动任意一个角,可以将9宫格拉大,或者缩小,两个手指缩放在9宫格中进行缩放,也可以将9宫格放大或缩小

4、点击确定,将9宫格框选的图片区域,裁剪成新的图片回调至上个页面。

HarmonyOS
2025-01-09 15:12:14
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
FengTianYa

示例参考如下:

//index.ets

import image from '@ohos.multimedia.image';
import { resourceManager } from '@kit.LocalizationKit';
import { RectPosition, ActionType, Position, InitPosition } from '../model/Bean'

const TAG = "IMAGE_CROPPING"

@Entry
@Component
struct Index {
  @Provide pixelMap: image.PixelMap | undefined = undefined;
  @Provide pixelMapBackUp: image.PixelMap | undefined = undefined;
  @Provide imageInfo: image.ImageInfo | undefined = undefined;
  private settings: RenderingContextSettings = new RenderingContextSettings(true);
  private canvasContext: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
  private settings2: RenderingContextSettings = new RenderingContextSettings(true);
  private canvasContext2: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings2);
  private settings3: RenderingContextSettings = new RenderingContextSettings(true);
  private canvasContext3: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings3);
  private actionType: ActionType = ActionType.move;
  private rotateOn: boolean = false
  @State imageArea: RectPosition = {
    x: 0,
    y: 0,
    width: 0,
    height: 0
  };
  private touchPosition: Position = {
    x: 0,
    y: 0,
  };
  private initPosition: InitPosition = {
    x: 0,
    y: 0,
    width: 0,
    height: 0,
  }
  @State isCrop: boolean = false
  @State cropImageInfo: image.ImageInfo | undefined = undefined;
  @State pixelMapChange: boolean = false
  @State @Watch('drawMask') clipRect: RectPosition = {
    x: 0,
    y: 0,
    height: 0,
    width: 0
  };

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      if (this.isCrop) {
        if (this.pixelMapChange) {
          Image(this.pixelMap)
            .width(px2vp(this.cropImageInfo?.size.width))
            .height(px2vp(this.cropImageInfo?.size.height))
            .margin({ top: '10%' })
        } else {
          Image(this.pixelMap)
            .width(px2vp(this.cropImageInfo?.size.width))
            .height(px2vp(this.cropImageInfo?.size.height))
            .margin({ top: '10%' })
        }

      } else {
        Canvas(this.canvasContext)
          .width(px2vp(this.imageInfo?.size.width))
          .height(px2vp(this.imageInfo?.size.height))
          .onReady(() => {
            this.drawImage()
          })
          .onAreaChange((value: Area, newVal: Area) => {
            // 获取图片位置xy
            this.initPosition.x = Math.round(newVal.position.x as number)
            this.initPosition.y = Math.round(newVal.position.y as number)
          })
        // 蒙层
        Canvas(this.canvasContext3)
          .position({
            x: this.initPosition.x,
            y: this.initPosition.y
          })
          .width(px2vp(this.imageInfo?.size.width))
          .height(px2vp(this.imageInfo?.size.height))
        // 裁剪框
        Canvas(this.canvasContext2)
          .position({
            x: this.clipRect.x,
            y: this.clipRect.y
          })
          .width(this.clipRect.width)
          .height(this.clipRect.height)
          .onReady(() => {
            this.drawClipImage()
          })
          .onTouch(event => {
            if (event.type === TouchType.Down) {
              this.isMove(event.target.area, event.touches[0]);
              this.touchPosition = {
                x: event.touches[0].screenX,
                y: event.touches[0].screenY
              }
            } else if (event.type === TouchType.Move) {
              let moveX = event.changedTouches[0].screenX - this.touchPosition.x;
              let moveY = event.changedTouches[0].screenY - this.touchPosition.y;
              this.touchPosition = {
                x: event.changedTouches[0].screenX,
                y: event.changedTouches[0].screenY
              }
              this.moveClipCanvas(moveX, moveY);
            }
          })
      }
      Row() {
        Image($rawfile('rotate.png'))
          .width(40)
          .height(40)
          .onClick(() => {
            this.rotateImage()
          })
      }
      .margin({ top: 50 })
      .height('7%')
      .width('100%')
      .padding(30)

      Row() {
        Image($rawfile('reset.png'))
          .width(40)
          .height(40)
          .onClick(() => {
            this.cancel()
          })
        Image($rawfile('crop.png'))
          .width(40)
          .height(40)
          .onClick(() => {
            this.clipImage()
          })
      }
      .margin({ top: 10 })
      .width('100%')
      .height('7%')
      .padding(30)
      .justifyContent(FlexAlign.SpaceBetween)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#000000')
  }

  // 旋转图片
  async rotateImage() {
    if (this.rotateOn) {
      await this.pixelMap?.rotate(90)
      const info = await this.pixelMap?.getImageInfo()
      this.cropImageInfo = info
      if (this.pixelMapChange) {
        this.pixelMapChange = false
      } else {
        this.pixelMapChange = true
      }
    }
  }

  // 取消剪切
  cancel() {
    this.pixelMap = this.pixelMapBackUp
    this.isCrop = false
    this.rotateOn = false
  }

  // 判断操作类型
  isMove(area: Area, touch: TouchObject) {
    if (touch.x < 60 && touch.y < 60) { // 左上角
      this.actionType = ActionType.topLeft
    } else if (touch.x < 60 && touch.y > (Number(area.height) - 60)) { // 左下
      this.actionType = ActionType.bottomLeft
    } else if (touch.x > Number(area.width) - 60 && touch.y < 60) { // 右上
      this.actionType = ActionType.topRight
    } else if (touch.x > Number(area.width) - 60 && touch.y > (Number(area.height) - 60)) { // 右下
      this.actionType = ActionType.bottomRight
    } else {
      this.actionType = ActionType.move
    }
  }

  // 绘制背景图
  async drawImage() {
    await this.initData('test.jpg')
    if (this.imageInfo != undefined) {
      this.canvasContext.drawImage(this.pixelMap, 0, 0, px2vp(this.imageInfo.size.width),
        px2vp(this.imageInfo.size.height));
      this.canvasContext.save();
    }
  }

  // 绘制蒙层
  drawMask() {
    this.canvasContext3.clearRect(0, 0, this.imageInfo?.size.width, this.imageInfo?.size.height);
    this.canvasContext3.fillStyle = 'rgba(0,0,0,0.7)';
    this.canvasContext3.fillRect(0, 0, px2vp(this.imageInfo?.size.width), px2vp(this.imageInfo?.size.height));
    this.canvasContext3.clearRect(this.clipRect.x - this.initPosition.x, this.clipRect.y - this.initPosition.y,
      this.clipRect.width, this.clipRect.height);
  }

  // 绘制裁剪框
  drawClipImage() {
    this.canvasContext2.clearRect(0, 0, this.clipRect.width, this.clipRect.height);
    this.canvasContext2.lineWidth = 6
    this.canvasContext2.strokeStyle = '#ffffff'
    this.canvasContext2.beginPath()

    this.canvasContext2.moveTo(0, 20)
    this.canvasContext2.lineTo(0, 0);
    this.canvasContext2.lineTo(20, 0);

    this.canvasContext2.moveTo(this.clipRect.width - 20, 0);
    this.canvasContext2.lineTo(this.clipRect.width, 0);
    this.canvasContext2.lineTo(this.clipRect.width, 20);

    this.canvasContext2.moveTo(0, this.clipRect.height - 20);
    this.canvasContext2.lineTo(0, this.clipRect.height);
    this.canvasContext2.lineTo(20, this.clipRect.height);

    this.canvasContext2.moveTo(this.clipRect.width - 20, this.clipRect.height);
    this.canvasContext2.lineTo(this.clipRect.width, this.clipRect.height);
    this.canvasContext2.lineTo(this.clipRect.width, this.clipRect.height - 20);
    this.canvasContext2.stroke()

    this.canvasContext2.beginPath();
    this.canvasContext2.lineWidth = 0.5;
    let height = Math.round(this.clipRect.height / 3);
    for (let index = 0; index <= 3; index++) {
      let y = index === 3 ? this.clipRect.height : height * index;
      this.canvasContext2.moveTo(0, y);
      this.canvasContext2.lineTo(this.clipRect.width, y);
    }
    let width = Math.round(this.clipRect.width / 3);
    for (let index = 0; index <= 3; index++) {
      let x = index === 3 ? this.clipRect.width : width * index;
      this.canvasContext2.moveTo(x, 0);
      this.canvasContext2.lineTo(x, this.clipRect.height);
    }
    this.canvasContext2.stroke();
  }

  // 获取pixelMap与imageInfo
  async initData(fileName: string) {
    const context: Context = getContext(this);
    const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
    const fileData = await resourceMgr.getRawFileContent(fileName);
    const buffer = fileData.buffer;
    const imageSource: image.ImageSource = image.createImageSource(buffer);
    const pixelMap: image.PixelMap = await imageSource.createPixelMap()
    this.pixelMap = pixelMap
    this.pixelMapBackUp = pixelMap
    const imageInfo = await pixelMap.getImageInfo()
    this.imageInfo = imageInfo
    // 裁剪框初始位置
    this.initPosition.width = px2vp(Math.round(this.imageInfo.size.width))
    this.initPosition.height = px2vp(Math.round(this.imageInfo.size.height))
    this.clipRect.height = px2vp(this.imageInfo.size.height)
    this.clipRect.width = px2vp(this.imageInfo.size.width)
    this.clipRect.x = this.initPosition.x
    this.clipRect.y = this.initPosition.y
  }

  // 裁剪图片
  async clipImage() {
    let x = this.clipRect.x - this.initPosition.x;
    let y = this.clipRect.y - this.initPosition.y;
    console.log('x= ' + x + ' y = ' + y + 'height = ' + this.clipRect.height + 'width = ' + this.clipRect.width)
    await this.pixelMap?.crop({
      x: vp2px(x),
      y: vp2px(y),
      size: { height: vp2px(this.clipRect.height), width: vp2px(this.clipRect.width) }
    })
    this.cropImageInfo = await this.pixelMap?.getImageInfo();
    this.isCrop = true
    this.rotateOn = true
  }

  // 裁剪框位置和大小变化 初始位置为图片的初始坐标 移动的坐标
  moveClipCanvas(moveX: number, moveY: number) {
    let clipRect: RectPosition = {
      x: this.clipRect.x,
      y: this.clipRect.y,
      width: this.clipRect.width,
      height: this.clipRect.height
    }
    switch (this.actionType) {
      case ActionType.move:
        clipRect.x += moveX;
        clipRect.y += moveY;
        break;
      case ActionType.topLeft:
        clipRect.x += moveX;
        clipRect.y += moveY;
        clipRect.width += -moveX;
        clipRect.height += -moveY;
        break;
      case ActionType.topRight:
        clipRect.y += moveY;
        clipRect.width += moveX;
        clipRect.height += -moveY;
        break;
      case ActionType.bottomLeft:
        clipRect.x += moveX;
        clipRect.width += -moveX;
        clipRect.height += moveY;
        break;
      case ActionType.bottomRight:
        clipRect.width += moveX;
        clipRect.height += moveY;
        break;
      default:
        break;
    }

    // 偏移坐标小于初始位置
    if (clipRect.x < this.initPosition.x) {
      clipRect.x = this.initPosition.x;
    }

    if (clipRect.y < this.initPosition.y) {
      clipRect.y = this.initPosition.y;
    }

    // 横坐标限制位置
    if (clipRect.width + clipRect.x > this.initPosition.width + this.initPosition.x) {
      if (this.actionType === ActionType.move) {
        clipRect.x = this.initPosition.width + this.initPosition.x - clipRect.width;
      } else {
        clipRect.width = this.initPosition.width + this.initPosition.x - clipRect.x;
      }
    }

    // 纵坐标限制
    if (clipRect.height + clipRect.y > this.initPosition.height + this.initPosition.y) {
      if (this.actionType === ActionType.move) {

        clipRect.y = this.initPosition.height + this.initPosition.y - clipRect.height;
      } else {

        clipRect.height = this.initPosition.height + this.initPosition.y - clipRect.y;
      }
    }

    this.clipRect = {
      x: Math.round(clipRect.x),
      y: Math.round(clipRect.y),
      width: Math.round(clipRect.width),
      height: Math.round(clipRect.height)
    };
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
  • 222.
  • 223.
  • 224.
  • 225.
  • 226.
  • 227.
  • 228.
  • 229.
  • 230.
  • 231.
  • 232.
  • 233.
  • 234.
  • 235.
  • 236.
  • 237.
  • 238.
  • 239.
  • 240.
  • 241.
  • 242.
  • 243.
  • 244.
  • 245.
  • 246.
  • 247.
  • 248.
  • 249.
  • 250.
  • 251.
  • 252.
  • 253.
  • 254.
  • 255.
  • 256.
  • 257.
  • 258.
  • 259.
  • 260.
  • 261.
  • 262.
  • 263.
  • 264.
  • 265.
  • 266.
  • 267.
  • 268.
  • 269.
  • 270.
  • 271.
  • 272.
  • 273.
  • 274.
  • 275.
  • 276.
  • 277.
  • 278.
  • 279.
  • 280.
  • 281.
  • 282.
  • 283.
  • 284.
  • 285.
  • 286.
  • 287.
  • 288.
  • 289.
  • 290.
  • 291.
  • 292.
  • 293.
  • 294.
  • 295.
  • 296.
  • 297.
  • 298.
  • 299.
  • 300.
  • 301.
  • 302.
  • 303.
  • 304.
  • 305.
  • 306.
  • 307.
  • 308.
  • 309.
  • 310.
  • 311.
  • 312.
  • 313.
  • 314.
  • 315.
  • 316.
  • 317.
  • 318.
  • 319.
  • 320.
  • 321.
  • 322.
  • 323.
  • 324.
  • 325.
  • 326.
  • 327.
  • 328.
  • 329.
  • 330.
  • 331.
  • 332.
  • 333.
  • 334.
  • 335.
  • 336.
  • 337.
  • 338.
  • 339.
  • 340.
  • 341.
  • 342.
  • 343.
  • 344.
  • 345.
  • 346.
  • 347.
  • 348.
  • 349.
  • 350.
  • 351.
  • 352.
  • 353.
  • 354.
  • 355.
  • 356.

model文件夹下的Bean.ets文件:

export interface RectPosition {
  x: number;
  y: number;
  height: number;
  width: number;
}

export enum ActionType {
  topLeft,
  topRight,
  bottomLeft,
  bottomRight,
  move
}

export interface Position {
  x: number;
  y: number;
}


export interface InitPosition {
  x: number;
  y: number;
  width: number;
  height: number;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
分享
微博
QQ
微信
回复
2025-01-09 18:24:07


相关问题
如何对相册图片进行编辑裁剪
2550浏览 • 1回复 待解决
API 9 ETS如何进行压缩图片
767浏览 • 1回复 待解决
如何实现图片裁剪、旋转
1210浏览 • 1回复 待解决
HarmonyOS 图片裁剪问题
562浏览 • 1回复 待解决
HarmonyOS 如何进行sdk升级
599浏览 • 1回复 待解决
HarmonyOS 如何进行代码检查
700浏览 • 1回复 待解决
HarmonyOS 如何进行邀请测试
700浏览 • 1回复 待解决
HarmonyOS 如何进行音频合成
978浏览 • 1回复 待解决
HarmonyOS 请问如何进行UrlEncode
604浏览 • 1回复 待解决
HarmonyOS image如何图片裁剪成圆形
465浏览 • 1回复 待解决
如何编辑裁剪相册中的图片
1469浏览 • 1回复 待解决
HarmonyOS 有没有图片裁剪控件?
593浏览 • 1回复 待解决
HarmonyOS 如何进行DES加解密
1313浏览 • 1回复 待解决
HarmonyOS如何进行模拟定位?
450浏览 • 1回复 待解决
HarmonyOS HAP之间如何进行通信?
1004浏览 • 1回复 待解决
HarmonyOS 如何进行堆栈反解
382浏览 • 1回复 待解决
HarmonyOS 选择图片裁剪的功能
753浏览 • 1回复 待解决
恭喜您,今日已阅读两篇内容,特奖励+2声望, 快来领取吧。