在HarmonyOS NEXT开发中如何获取空间的宽高以及在屏幕中的坐标?
在 HarmonyOS NEXT 开发中,可以通过 ArkUI 组件的 onAreaChange
事件回调获取组件的宽高和屏幕坐标。具体实现方式如下:
// 示例:获取 Text 组件的宽高和屏幕坐标
@Entry
@Component
struct Index {
@State componentWidth: number = 0
@State componentHeight: number = 0
@State screenX: number = 0
@State screenY: number = 0
build() {
Column() {
Text('Target Component')
.onAreaChange((oldArea: Area, newArea: Area) => {
// 获取组件宽高
this.componentWidth = newArea.width
this.componentHeight = newArea.height
// 获取屏幕坐标(相对于屏幕左上角)
this.screenX = newArea.globalPosition.x
this.screenY = newArea.globalPosition.y
})
// 显示测量结果
Text(`Width: ${this.componentWidth}, Height: ${this.componentHeight}`)
Text(`Screen Position: (${this.screenX}, ${this.screenY})`)
}
}
}
关键说明:
onAreaChange
在以下情况触发:
newArea
对象包含:
width
:组件宽度height
:组件高度globalPosition
:包含 x/y 坐标的对象(相对于屏幕左上角)注意事项:
position
属性
onAreaChange()
参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-refere...