HarmonyOS 分屏模式,图片跨应用拖拽

分屏拖拽图片到备忘录,图片不展示。对应代码中,图片拖拽时也没调起中转站的应用。而Text却没有问题。

应用代码如下:

import { uniformTypeDescriptor as UTD,unifiedDataChannel as UDC } from '@kit.ArkData';
import { componentSnapshot, promptAction } from '@kit.ArkUI';
import  {pasteboard,BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  controller: RichEditorController = new RichEditorController();
  @State targetImage: string | PixelMap = '';
  @State targetDragImage: string | PixelMap = '';
  @State targetText: string = 'Drag Text';
  @State imageWidth: number = 100;
  @State imageHeight: number = 100;
  @State imgState: Visibility = Visibility.Visible;
  @State abstractContent: string = "abstract";
  @State textContent: string = "";
  @State backGroundColor: Color = Color.Transparent;

  onCreateMenu(menuItems: Array<TextMenuItem>) {
    menuItems.forEach((value, index) => {
      value.icon = $r('app.media.startIcon')
      if (value.id.equals(TextMenuItemId.COPY)) {
        value.content = "复制change"
      }
      if (value.id.equals(TextMenuItemId.SELECT_ALL)) {
        value.content = "全选change"
      }
    })
    let item1: TextMenuItem = {
      content: 'custom1',
      icon: $r('app.media.startIcon'),
      id: TextMenuItemId.of('custom1'),
    }
    let item2: TextMenuItem = {
      content: 'custom2',
      id: TextMenuItemId.of('custom2'),
      icon: $r('app.media.startIcon'),
    }
    menuItems.push(item1)
    menuItems.unshift(item2)
    return menuItems
  }

  getDataFromUdmfRetry(event: DragEvent, callback: (data: DragEvent) => void) {
    try {
      let data: UnifiedData = event.getData();
      if (!data) {
        return false;
      }
      let records: Array<UDC.UnifiedRecord> = data.getRecords();
      if (!records || records.length <= 0) {
        return false;
      }
      callback(event);
      return true;
    } catch (e) {
      console.log("getData failed, code = " + (e as BusinessError).code + ", message = " +
      (e as BusinessError).message);
      return false;
    }
  }

  getDataFromUdmf(event: DragEvent, callback: (data: DragEvent) => void) {
    if (this.getDataFromUdmfRetry(event, callback)) {
      return;
    }
    setTimeout(() => {
      this.getDataFromUdmfRetry(event, callback);
    }, 1500);
  }

  private PreDragChange(preDragStatus: PreDragStatus): void {
    if (preDragStatus == PreDragStatus.READY_TO_TRIGGER_DRAG_ACTION) {
      this.backGroundColor = Color.Red;
    } else if (preDragStatus == PreDragStatus.ACTION_CANCELED_BEFORE_DRAG ||
      preDragStatus == PreDragStatus.PREVIEW_LANDING_FINISHED) {
      this.backGroundColor = Color.Blue;
    }
  }

  build() {
    Row() {
      Column() {
        Text('start Drag')
          .fontSize(18)
          .width('100%')
          .height(40)
          .margin(10)
          .backgroundColor('#008888')
        Text('this is drag image test,top,top,top,top,top,')
          .copyOption(CopyOptions.InApp)
        Image($r('app.media.hi2243701019'))
          .width(120)
          .height(120)
          .draggable(false)
          .margin({ left: 15 })
          .visibility(this.imgState)
          .onDragEnd((event) => {
            // onDragEnd里取到的result值在接收方onDrop设置
            if (event.getResult() === DragResult.DRAG_SUCCESSFUL) {
              promptAction.showToast({ duration: 100, message: 'Drag Success' });
            } else if (event.getResult() === DragResult.DRAG_FAILED) {
              promptAction.showToast({ duration: 100, message: 'Drag failed' });
            }
          })
          .id('imageId')
          .gesture(
            LongPressGesture({duration:1000})
              .onAction(async () => {
                console.log('长按')
                let pixmap = await componentSnapshot.get('imageId');
                // let pasteData: pasteboard.PasteData = pasteboard.createRecord(pasteboard.MIMETYPE_PIXELMAP, pixmap);
                let pasteData: pasteboard.PasteData = pasteboard.createData(pasteboard.MIMETYPE_PIXELMAP, pixmap);
                this.targetImage = pixmap;
                // 将数据写入系统剪贴板
                let systemPasteboard = pasteboard.getSystemPasteboard();
                systemPasteboard.setData(pasteData);
                promptAction.showToast({ duration: 100, message: 'Copy Success' });
              })
          )
        Image($r('app.media.2238350494'))
          .width(120)
          .height(120)
          .draggable(true)
          .margin({ left: 15 })

        Text('this is bottom text bottom,bottom,bottom,bottom,bottom,bottom,')
          .copyOption(CopyOptions.LocalDevice)
        Text('this is drag text')
          .width('100%')
          .height(50)
          .draggable(true)
          .margin({ left: 15 })
            // 设置文本选择复制方式,https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-appendix-enums-V5#copyoptions9
          .copyOption(CopyOptions.InApp)
          .editMenuOptions({
            // return true 则使用自己的处理方式,return false则使用默认的处理方式
            onCreateMenu: this.onCreateMenu, onMenuItemClick: (menuItem: TextMenuItem, textRange: TextRange) => {
              if (menuItem.id.equals(TextMenuItemId.of("custom2"))) {
                promptAction.showToast({ duration: 100, message: 'test drag event'.substring(textRange.start, textRange.end) });
                console.log("拦截 id: custom2 start:" + JSON.stringify(textRange))
                console.log("拦截 id: custom2 start:" + JSON.stringify(menuItem))
                return true;
              }
              if (menuItem.id.equals(TextMenuItemId.COPY)) {
                console.log("不拦截 COPY start:" + textRange.start + "; end:" + textRange.end)
                return false;
              }
              if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
                console.log("不拦截 SELECT_ALL start:" + textRange.start + "; end:" + textRange.end)
                return false;
              }
              return false;
            }
          })

        Column() {
          Text('this is abstract').fontSize(20).width('100%')
        }
        .margin({ left: 40, top: 20 })
        .width('100%')
        .height(50)
        .backgroundColor(this.backGroundColor)
        .onDragStart((event) => {
          this.backGroundColor = Color.Transparent;
          let data: UDC.PlainText = new UDC.PlainText();
          data.abstract = 'this is abstract';
          data.textContent = 'this is abstract';
          (event as DragEvent).setData(new UDC.UnifiedData(data));
        })
        .onPreDrag((status: PreDragStatus) => {
          this.PreDragChange(status);
        })
        Text('RichEditor Area')
        RichEditor({ controller: this.controller })
          .onReady(() => {
            this.controller.addTextSpan("012345",
              {
                style:
                {
                  fontColor: Color.Orange,
                  fontSize: 30
                }
              })
            this.controller.addSymbolSpan($r("sys.symbol.ohos_trash"),
              {
                style:
                {
                  fontSize: 30
                }
              })
            this.controller.addImageSpan($r("app.media.hi2243701019"),
              {
                imageStyle:
                {
                  size: ["57px", "57px"]
                }
              })
            this.controller.addTextSpan("56789",
              {
                style:
                {
                  fontColor: Color.Black,
                  fontSize: 30
                }
              })
          })
          .onDrop((dragEvent?: DragEvent) => {
            this.getDataFromUdmf((dragEvent as DragEvent), (event: DragEvent) => {
              let records: Array<UDC.UnifiedRecord> = event.getData().getRecords();
              let rect: Rectangle = event.getPreviewRect();
              this.imageWidth = Number(rect.width);
              this.imageHeight = Number(rect.height);
              this.controller.getCaretOffset();
              this.controller.addImageSpan((records[0] as UDC.Image).imageUri,
                {
                  imageStyle:
                  {
                    size: ["75px", "75px"]
                  },
                  offset: this.controller.getCaretOffset()
                })
            })
          })
      }.width('45%').height('100%')

      Column() {
        Text('Drag Target Area')
          .fontSize(20)
          .width('100%')
          .height(40)
          .margin(10)
          .backgroundColor('#008888')
        Image(this.targetImage)
          .width(100)
          .height(100)
          .border({ color: Color.Black, width: 1 })
        Image(this.targetDragImage)
          .width(this.imageWidth)
          .height(this.imageHeight)
          .draggable(true)
          .margin({ left: 15 })
          .border({ color: Color.Black, width: 1 })
          .allowDrop([UTD.UniformDataType.IMAGE])
          .onDrop((dragEvent?: DragEvent) => {
            this.getDataFromUdmf((dragEvent as DragEvent), (event: DragEvent) => {
              let records: Array<UDC.UnifiedRecord> = event.getData().getRecords();
              let rect: Rectangle = event.getPreviewRect();
              this.imageWidth = Number(rect.width);
              this.imageHeight = Number(rect.height);
              this.targetDragImage = (records[0] as UDC.Image).imageUri;
              event.useCustomDropAnimation = false;
              // 显式设置result为successful,则将该值传递给拖出方的onDragEnd
              event.setResult(DragResult.DRAG_SUCCESSFUL);
            })
          })

        Text(this.targetText)
          .width('100%')
          .height(100)
          .border({ color: Color.Black, width: 1 })
          .margin(15)
          .allowDrop([UTD.UniformDataType.PLAIN_TEXT])
          .onDrop((dragEvent?: DragEvent) => {
            this.getDataFromUdmf((dragEvent as DragEvent), (event: DragEvent) => {
              let records: Array<UDC.UnifiedRecord> = event.getData().getRecords();
              let plainText: UDC.PlainText = records[0] as UDC.PlainText;
              this.targetText = plainText.textContent;
            })
          })

        Column() {
          Text(this.abstractContent).fontSize(20).width('100%')
          Text(this.textContent).fontSize(15).width('100%')
        }
        .width('100%')
        .height(100)
        .margin(20)
        .border({ color: Color.Black, width: 1 })
        .allowDrop([UTD.UniformDataType.PLAIN_TEXT])
        .onDrop((dragEvent?: DragEvent) => {
          this.getDataFromUdmf((dragEvent as DragEvent), (event: DragEvent) => {
            let records: Array<UDC.UnifiedRecord> = event.getData().getRecords();
            let plainText: UDC.PlainText = records[0] as UDC.PlainText;
            this.abstractContent = plainText.abstract as string;
            this.textContent = plainText.textContent;
          })
        })

        TextArea({ placeholder: 'please input words' })
          .copyOption(CopyOptions.InApp)
          .width('100%')
          .height(50)
          .draggable(true)
        Search({ placeholder: 'please input you word' })
          .searchButton('Search')
          .width('100%')
          .height(80)
          .textFont({ size: 20 })
      }.width('45%').height('100%').margin({ left: '5%' })
    }.height('100%')
  }
}
HarmonyOS
2天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

两个问题都是因为资源文件都存在于本应用中,中转站和备忘录都没有权限获取对应文件。因此没有调起中转站,拖到备忘录也没有展示出来。

使用pixelMap作为图片的数据源让其他应用可以看到就能实现对应功能。

Image(this.context.resourceManager.getDrawableDescriptor($r('app.media.2238350494').id).getPixelMap())
分享
微博
QQ
微信
回复
2天前
相关问题
HarmonyOS 如何关闭分屏模式
177浏览 • 1回复 待解决
HarmonyOS 怎么禁用分屏模式
111浏览 • 1回复 待解决
HarmonyOS分屏模式和小窗口模式适配
912浏览 • 1回复 待解决
HarmonyOS 分屏模式界面如何适配
128浏览 • 1回复 待解决
HarmonyOS 如何禁用小窗和分屏模式
527浏览 • 1回复 待解决
HarmonyOS 分屏模式下页面无法滑动
25浏览 • 1回复 待解决
HarmonyOS 应用怎么禁用分屏
122浏览 • 1回复 待解决
HarmonyOS 如何禁止应用分屏
126浏览 • 1回复 待解决
HarmonyOS 图片拖拽实现
247浏览 • 1回复 待解决
HarmonyOS 应用内如何实现分屏
25浏览 • 1回复 待解决
如何禁止应用分屏和小窗展示
2218浏览 • 1回复 待解决
HarmonyOS 加载图片域错误
27浏览 • 1回复 待解决