快速上手Grid拖拽交换子组件位置


/**
 * 构建图库UI主页面
 */
// 导入模块
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';

@Entry
@Component
struct Page {
  @State title: string = '图库';
  @State pictureArray: Resource[] = [$r('app.media.pic_1'), $r("app.media.pic_2"), $r('app.media.pic_3')
  ];
  @State addPic: Resource = $r('app.media.addPic');
  private picTemp: Resource;
  @State pictureZIndex: number = 0;
  @State isSelect: boolean = false;
  private selectedPicture: number[] = [];
  /**
   * 图片添加方法:
   * 从手机相册添加图片
   */
  addPicture = async () => {
    const photoSelectOptions = new picker.PhotoSelectOptions();
    photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
    photoSelectOptions.maxSelectNumber = 5; // 选择媒体文件的最大数目
    let URI = null;
    const photoViewPicker = new picker.PhotoViewPicker();
    photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
      URI = photoSelectResult.photoUris
      this.pictureArray = this.pictureArray.concat(URI)

      let file = fs.openSync(URI, fs.OpenMode.READ_ONLY);
      console.info('===file fd: ' + file.fd);
      let buffer = new ArrayBuffer(4096);
      let readLen = fs.readSync(file.fd, buffer);
      console.info('===readSync data to file succeed and buffer size is:' + readLen);
      fs.closeSync(file);
    }).catch((err) => {
      console.error(`===Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
    })
  }

  //拖拽过程中展示的样式
  @Builder pixelMapBuilder() {
    Image(this.picTemp)
      .height(66)
      .objectFit(ImageFit.Contain)
  }

  //交换数组中元素位置
  changeIndex(index1: number, index2: number) {
    let temp = this.pictureArray[index1]
    this.pictureArray[index1] = this.pictureArray[index2]
    this.pictureArray[index2] = temp
  }

  build() {
    Column() {
      Text(this.title)
        .fontSize(30)
        .fontWeight(FontWeight.Bold)
        .width('100%')
        .textAlign(TextAlign.Center)
        .padding(6)
        .backgroundColor("#aee4d8")

      Divider()
        .strokeWidth(5)
        .shadow({ radius: 3, color: "#F5F5F5", offsetX: 5, offsetY: 10 })
      // 图片展示的UI布局
      Column() {
        // 网格组件展示图片
        Grid() {
          // ForEach 循环渲染 UI 布局展示APP中内置的图片
          ForEach(this.pictureArray.slice(0, this.pictureArray.length - 1), (item, index) => {
            GridItem() {
              Image(item)
                .width('100%')
                .objectFit(ImageFit.Contain)
                .onTouch((event: TouchEvent) => {
                  if (event.type === TouchType.Down) {
                    this.picTemp = item
                  }
                })
            }
          })

          GridItem() {
            Image(this.addPic)
              .width('100%')
              .objectFit(ImageFit.Fill)
          }
          .onClick(this.addPicture)
        }
        //设置Grid是否进入编辑模式,进入编辑模式可以拖拽Grid组件内部GridItem
        .editMode(true)
        .columnsTemplate('1fr 1fr 1fr')
        .rowsGap(3)
        .columnsGap(3)
        .onScrollIndex((first: number) => {
          console.info("====" + first.toString())
        })
        //第一次拖拽此事件绑定的组件时,触发回调
        .onItemDragStart((event: ItemDragInfo, itemIndex: number) => {
          //设置拖拽过程中显示的图片
          return this.pixelMapBuilder()
        })
        //绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调
        //itemIndex为拖拽起始位置,insertIndex为拖拽插入位置
        .onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => {
          //不支持拖拽到已有内容以外的位置
          if (insertIndex < this.pictureArray.length - 1) {
            this.changeIndex(itemIndex, insertIndex)
          }
        })
      }
      .height("80%")
      .width('100%')
    }
    .height("100%")
    .justifyContent(FlexAlign.Start)
  }
}`在这里插入代码片`
  • 21
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值