文档开发者中心
我的

HarmonyOS7 碰一碰精准分享,坐标命中组件实战

浏览12发布于2026-11-16 04:31广东

很多人用过鸿蒙碰一碰传文件,但传统方式只能预先选好内容再碰。API26 新增的 knockShare 坐标能力,实现 “碰哪里传哪里”,PC 文档里碰段落就插入图片、相册碰对应图片就发送。坑点集中在坐标体系换算,屏幕 px 和组件 vp 很容易混,直接对比必然命中失败。

核心要点:回调拿到的 screenX、screenY 是屏幕像素,不是窗口相对坐标;用getRectangleById获取组件的 screenOffset,和碰击坐标同坐标系,直接做矩形判断。还要处理坐标为空、组件还没布局完成的兜底,没命中时调用 clarifyNonShare 终止分享,避免用户一直等待转圈。

收起
自动换行
深色代码主题
复制
// knockHit.ets 工具函数
import { UIContext } from '@ohos.arkui.UIContext';

export function hitComponent(ctx: UIContext, compId: string, x: number, y: number): boolean {
  try {
    const rectInfo = ctx.getComponentUtils().getRectangleById(compId);
    const left = rectInfo.screenOffset.x;
    const top = rectInfo.screenOffset.y;
    const right = left + rectInfo.size.width;
    const bottom = top + rectInfo.size.height;
    return x >= left && x <= right && y >= top && y <= bottom;
  } catch (err) {
    // 组件未挂载、不在屏幕内直接返回不命中
    return false;
  }
}
收起
自动换行
深色代码主题
复制
// 接收端页面示例:文档区域,碰击位置插入图片
import { harmonyShare } from '@kit.ShareKit';
import { utd } from '@kit.ArkData';

@Entry
@Component struct DocEditPage {
  @State docContent: string[] = ['第一段文字','第二段文字','第三段文字'];
  private shareOff?: () => void;

  aboutToAppear() {
    this.shareOff = harmonyShare.on('dataReceive', async (recvTarget) => {
      const info = recvTarget.getInfo();
      const pos = info.coordinate;
      if (!pos) return;
      const uiCtx = this.getUIContext();
      // 遍历段落组件,找到命中的段落id
      const hitIndex = this.docContent.findIndex((_, idx)=>{
        return hitComponent(uiCtx, `para_${idx}`, pos.screenX, pos.screenY);
      })
      if(hitIndex >=0){
        // 在命中段落之后插入图片占位
        this.docContent.splice(hitIndex+1,0,'[插入图片]')
      }
    })
  }
  aboutToDisappear() {
    this.shareOff?.();
  }
  build() {
    Column(){
      ForEach(this.docContent, (item,idx)=>{
        Text(item)
          .id(`para_${idx}`)
          .fontSize(18)
          .margin({bottom:12})
      })
    }.padding(20)
  }
}
收藏
0
回复
0
分享
全部评论
暂无评论
暂无评论
写评论
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。
发表
我要写文章
了解社区公约,与您携手共创和谐专业的开发者社区。