HarmonyOS 鸿蒙Next 悬浮按钮到达屏幕边缘时不可再往屏幕外移动 该如何实现
HarmonyOS 鸿蒙Next 悬浮按钮到达屏幕边缘时不可再往屏幕外移动 该如何实现
请问各位–如下这段代码,是一个悬浮按钮,我想实现,让这个按钮不超过屏幕的边框,该怎么做?
@Entry
@Componentstruct Section_4_item {
build() {
Column() {
FilerBall({
positionX: 0,
positionY: 0,
})
}
.position({ x: 0, y: 0 }) // 因为呈现悬浮态,所以要设置初始绝对坐标,对应positionX、positionY参数,用于悬浮球拖动效果(必需)
.zIndex(1) // 置于窗口最上层(必需)
.width(300) // 宽高可设置在父组件,也可传入FilerBall参数Width、Height
.height(500)
.backgroundColor('#C0C0C0')
}
}
@Componentstruct FilerBall {
@State gx: number = 0
@State gy: number = 0
@Prop positionX: number // FilerBall 组件的传参
@Prop positionY: number // FilerBall 组件的传参
private px = 0
private py = 0
build() {
Column() {
Button()
.width(100)
.height(100)
.onTouch((event:TouchEvent) => {
if (event.type === TouchType.Move) {
this.gx = event.touches[0].screenX - this.px - this.positionX
this.gy = event.touches[0].screenY - this.py - this.positionY
}
else if (event.type === TouchType.Down) {
this.px = event.touches[0].x
this.py = event.touches[0].y
}
})
}
.position({ x: this.gx, y: this.gy }) // 要拖拽的组件
}
}
更多关于HarmonyOS 鸿蒙Next 悬浮按钮到达屏幕边缘时不可再往屏幕外移动 该如何实现的实战教程也可以访问 https://www.itying.com/category-93-b0.html
更多关于HarmonyOS 鸿蒙Next 悬浮按钮到达屏幕边缘时不可再往屏幕外移动 该如何实现的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
可以设置这球的位置position最大最小值,最小值就是最左侧,最大值就是最右侧,超出最大最小值的时候等于最大最小值。
好的好的,,
我的理解是获取屏幕绝对宽度?根据按钮中心的位置加上圆形直径计算出最左侧的坐标?如果拿到初始坐标也许就可以了?
拖曳事件有draggale属性可以设置,onDragXXX等可以用吧?
我也刚开始开发,只是一点思考,我没有实现过
在HarmonyOS中,实现悬浮按钮到达屏幕边缘时不可再往屏幕外移动的功能,可以通过以下步骤完成:
-
获取屏幕尺寸:首先,使用
WindowManager
或Display
相关API获取当前屏幕的宽度和高度。 -
监听触摸事件:为悬浮按钮设置
OnTouchListener
,监听用户的触摸操作,包括按下、移动和抬起等事件。 -
计算按钮位置:在
onTouch
事件中,根据触摸点的坐标计算悬浮按钮的新位置。 -
边界检测:在移动过程中,实时检测悬浮按钮是否接近屏幕边缘。如果按钮的左侧、右侧、顶部或底部坐标超出屏幕边界,则将其位置限制在屏幕内。
-
更新按钮位置:根据计算和边界检测的结果,更新悬浮按钮的位置,使其保持在屏幕内。
以下是一个简化的代码示例:
import { WindowManager, Display, UIComponent, TouchEvent } from 'ohos';
class FloatingButton extends UIComponent {
private screenWidth: number;
private screenHeight: number;
constructor() {
super();
const display = Display.getDefaultDisplay();
this.screenWidth = display.width;
this.screenHeight = display.height;
}
onTouch(event: TouchEvent): void {
const x = event.getX();
const y = event.getY();
// 计算新位置
let newX = this.getX() + x;
let newY = this.getY() + y;
// 边界检测
newX = Math.max(0, Math.min(newX, this.screenWidth - this.getWidth()));
newY = Math.max(0, Math.min(newY, this.screenHeight - this.getHeight()));
// 更新位置
this.setX(newX);
this.setY(newY);
}
}
通过上述步骤,可以确保悬浮按钮在移动时不会超出屏幕边界。