HarmonyOS 鸿蒙Next ArkUI stage 控制按钮拖动的范围

HarmonyOS 鸿蒙Next ArkUI stage 控制按钮拖动的范围 大家好,我遇到一个问题,我实现一个拖动的按钮。我想控制按钮拖动的范围,让它不超出这个范围外。我本来想得到窗口的大小然后长和宽减去一个数值。但是获取的context信息为undefined。

import common from '@ohos.app.ability.common';
import window from '@ohos.window';

@Component
export default struct PanAddComponent{
  @State offsetX: number = 0
  @State offsetY: number = 0
  @State positionX: number = 0;
  @State positionY: number = 0;
  private context = this as common.UIAbilityContext;
  
  build(){
    Button({ type: ButtonType.Circle, stateEffect: true }){
      Image($r("app.media.pr_tabs_add"))
    }
    .width(55)
    .height(55)
    .translate({x: this.offsetX, y: this.offsetY,z:0})
    .gesture(
      PanGesture()
        .onActionUpdate((event: GestureEvent) => {
          this.offsetX = this.positionX + event.offsetX;
          this.offsetY = this.positionY + event.offsetY;
        })
        .onActionEnd((event: GestureEvent) => {
          console.info("context:", JSON.stringify(this.context))
          window.getLastWindow(this.context, (err, data)=>{
            console.info("data:", JSON.stringify(data))
          })
          
          this.positionX = this.offsetX;
          this.positionY = this.offsetY;
        })
    )
  }
}
12-08 14:43:55.236 22424-29812 I A0c0d0/JSApp: app Log: context: undefined
12-08 14:47:15.131 28596-24236 I A0c0d0/JSApp: app Log: context: undefined
12-08 14:47:15.131 28596-24236 W A0c0d0/JSApp: app Log: window.getLastWindow interface mocked in the Previewer. How this interface works on the Previewer may be different from that on a real device.

更多关于HarmonyOS 鸿蒙Next ArkUI stage 控制按钮拖动的范围的实战教程也可以访问 https://www.itying.com/category-93-b0.html

5 回复

楼主,你有试过拖动只能限制在父容器中不,一直想实现这样的方式,就是有一个长方形的区域,子组件只能在这个区域中拖动,超出父组件边缘就不然滑动出去。试放之后,会自动就近靠边并带有动画的那种

更多关于HarmonyOS 鸿蒙Next ArkUI stage 控制按钮拖动的范围的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


这就是android中的fab控件,但是鸿蒙中好像没有这种基础组件。

楼主。范围这个问题解决了吗。

1.你获取的context,你测试过吗?如果没获取到,你加一个全局的context

用这种方式调用context

在HarmonyOS鸿蒙Next中,ArkUI的Stage模型允许开发者通过设置组件的布局和约束来控制按钮的拖动范围。具体来说,可以通过DragControllerDragEvent来实现按钮的拖动行为,并通过设置DragRange来限制按钮的拖动范围。

在Stage模型中,DragRange通常通过设置Rect类型的属性来定义按钮可以拖动的区域。例如,可以使用Rectlefttoprightbottom属性来指定一个矩形区域,按钮只能在这个区域内拖动。

代码示例:

import { DragController, DragEvent, Rect } from '@ohos.arkui';

class MyButton {
    private dragController: DragController;

    constructor() {
        this.dragController = new DragController();
        this.dragController.setDragRange(new Rect(0, 0, 300, 300)); // 设置拖动范围为300x300的矩形区域
    }

    onDrag(event: DragEvent) {
        // 处理拖动事件
    }
}

在这个示例中,setDragRange方法设置了按钮的拖动范围为一个300x300的矩形区域。按钮只能在这个区域内拖动,超出这个区域的拖动操作将被限制。

回到顶部