【HarmonyOS NEXT】鸿蒙获取手势触摸点的屏幕全局坐标
一、问题背景
在Android和IOS中,使用手势触摸事件的x,y坐标,做一些逻辑处理。比如拖动小窗口,滑动触摸响应tips文字内容等。都需要拿到手势触摸点的屏幕全局坐标。
比如根据手势x坐标,去提示对应区域的文字内容。
二、解决方案
通过平移手势,在动作开始前,动作中,动作后,三个回调触摸事件中,有fingerList属性,可以拿到FingerInfo对象,其中的global坐标可以拿到屏幕全局坐标。
根据业务需求的不同,可以挑选global,local,display三种类型的坐标使用。
注意:
因为获取到的坐标,都是相对于左上角的x轴坐标。所以在视觉处理上,我们要用图形中心点进行计算,例如一个拖动VIew,计算其中心点,就是宽高/2。所以拿到的x,y就需要再加上宽高/2。
三、DEMO示例:
@Entry
@Component
struct GesturePage {
private TAG: string = "GesturePage";
@State mX: number = 0;
@State mY: number = 0;
build() {
Column(){
Column(){
Text("X : " + this.mX)
Text("Y : " + this.mY)
}
.size({
width: px2vp(600),
height: px2vp(200)
})
.backgroundColor(Color.Yellow)
.position({
x: this.mX,
y: this.mY
})
}
.height('100%')
.width('100%')
.backgroundColor(Color.Black)
.gesture(
PanGesture({
fingers: 1
})
.onActionStart((event: GestureEvent) => {
console.info(this.TAG, 'Pan start')
})
.onActionUpdate((event: GestureEvent) => {
if (event) {
let temp: FingerInfo[] =event.fingerList;
this.mX = temp[0].globalX;
this.mY = temp[0].globalY;
}
})
.onActionEnd((event: GestureEvent) => {
console.info(this.TAG, 'Pan end')
})
)
}
}