很多人用过鸿蒙碰一碰传文件,但传统方式只能预先选好内容再碰。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)
}
}







































苏公安网备 32011402010933号