HarmonyOS鸿蒙Next中SwipeGesture如何判断手势上下左右四大方向
HarmonyOS鸿蒙Next中SwipeGesture如何判断手势上下左右四大方向
如题如图,文档只有水平和垂直方向,而我需要的知道是左右上下,请问如何做?
2 回复
@Entry
@Component
struct test {
@State screenStartX: number = 0
@State screenStartY: number = 0
@State lastScreenX: number = 0
@State lastScreenY: number = 0
build() {
Column() {
Column() {}
.border({ width: 3 })
.width(300)
.height(200)
.margin(100)
.onTouch((e) => {
if (e.type === TouchType.Down && e.touches.length > 0) { // 触摸开始,记录初始位置
this.screenStartX = e.touches[0].screenX;
this.screenStartY = e.touches[0].screenY;
} else if (e.type === TouchType.Up && e.changedTouches.length > 0) { // 当手指抬起时,更新最后的位置
this.lastScreenX = e.changedTouches[0].screenX;
this.lastScreenY = e.changedTouches[0].screenY;
}
})
.gesture(
SwipeGesture({ direction: SwipeDirection.All }) //支持方向中 all可以是上下左右
.onAction((event: GestureEvent) => {
const swipeX = this.lastScreenX - this.screenStartX;
const swipeY = this.lastScreenY - this.screenStartY;
// 判断滑动方向
let directionText = '';
if (Math.abs(swipeX) > Math.abs(swipeY)) {
if (swipeX > 0) {
directionText = 'Right'; // 向右滑动
} else {
directionText = 'Left'; // 向左滑动
}
} else {
if (swipeY > 0) {
directionText = 'Down'; // 向下滑动
} else {
directionText = 'Up'; // 向上滑动
}
}
console.info('====滑动方向:', directionText);
// console.info('====起点x:', this.screenStartX);
// console.info('====起点y:', this.screenStartY);
// console.info('====终点x:', this.lastScreenX);
// console.info('====终点y:', this.lastScreenY);
// 清除开始位置记录,准备下一次滑动判断
this.screenStartX = 0;
this.screenStartY = 0;
})
)
}.width('100%')
}
}
更多关于HarmonyOS鸿蒙Next中SwipeGesture如何判断手势上下左右四大方向的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,SwipeGesture
可以通过监听onActionEnd
事件来判断手势方向。通过获取事件中的offsetX
和offsetY
值,可以判断滑动方向:若offsetX
为正,表示向右滑动;为负,表示向左滑动。若offsetY
为正,表示向下滑动;为负,表示向上滑动。结合绝对值比较,可以准确判断上下左右四大方向。