HarmonyOS鸿蒙Next中怎么获取某一个视图的起始位置?

HarmonyOS鸿蒙Next中怎么获取某一个视图的起始位置? 如何获取某一个视图的起始位置?

3 回复

通过给组件设置id,根据id获取位置信息: componentUtils.getRectangleById(对应Id);

import componentUtils from '@ohos.arkui.componentUtils';
@Component
struct Page1 {
  build() {
    Row() {
      Column() {
        Text('Hello World')
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .id('myText')
          .backgroundColor(Color.Yellow)
          .onClick(() =>{
            let modePosition: componentUtils.ComponentInfo = componentUtils.getRectangleById("myText");
            console.log('modePosition' + JSON.stringify(modePosition));
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

输出日志:

modePosition{"size":{"width":910,"height":197},"localOffset":{"x":175,"y":0},"windowOffset":{"x":175,"y":1279},"screenOffset":{"x":175,"y":1279},"translate":{"x":0,"y":0,"z":0},"scale":{"x":1,"y":1,"z":1,"centerX":14000,"centerY":3030.769230769231},"rotate":{"x":0,"y":0,"z":0,"angle":0,"centerX":14000,"centerY":3030.769230769231},"transform":[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}

对应值为px,可用px2vp()转成需要的值。

更多关于HarmonyOS鸿蒙Next中怎么获取某一个视图的起始位置?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,获取某一个视图的起始位置可以通过ComponentgetLocationOnScreen方法来实现。该方法可以获取视图在屏幕上的坐标位置。

具体步骤如下:

  1. 获取目标视图的Component对象。
  2. 调用getLocationOnScreen方法,该方法会返回一个包含x和y坐标的数组。
  3. 数组中的第一个元素是视图左上角在屏幕上的x坐标,第二个元素是y坐标。

示例代码:

let component = this.$element('yourComponentId'); // 获取Component对象
let location = component.getLocationOnScreen(); // 获取视图在屏幕上的位置
console.log(\`X坐标: \${location\[0\]}, Y坐标: \${location\[1\]}\`);

在HarmonyOS鸿蒙Next中,可以通过getLocationOnScreen方法获取视图的起始位置。该方法返回视图左上角在屏幕上的坐标。示例代码如下:

int[] location = new int[2];
view.getLocationOnScreen(location);
int startX = location[0];
int startY = location[1];

startXstartY分别为视图的起始X和Y坐标。

回到顶部