往期鸿蒙全套实战精彩文章必看内容:
如何获取组件宽高和组件在屏幕上的位置
方法一:可以使用componentUtils.getRectangleById,根据组件ID获取组件实例对象,通过组件实例对象将获取的坐标位置和大小同步返回给开发者。
getRectangleById的返回结果是ComponentInfo,包含组件大小、位置、平移缩放旋转及仿射矩阵属性信息。
具体可以参考如下代码:
import { componentUtils } from '@kit.ArkUI';
@Entry
@Component
struct Page {
@State arr: Array<number> = [1, 2, 3, 4, 5];
build() {
Column() {
List() {
ForEach(this.arr, (item: number) => {
ListItem() {
Text(item.toString())
.fontSize(24)
.id(item.toString())
}
.height(100)
})
}
.height('50%')
.alignListItem(ListItemAlign.Center)
Button('获取组件位置').onClick(() => {
let obj: componentUtils.ComponentInfo = componentUtils.getRectangleById('2');
console.log("demoTest:" + JSON.stringify(obj));
})
}
}
}
方法二:在组件尺寸发生变化时,需要使用onAreaChange可以响应由布局变化所导致的组件大小、位置发生变化时的回调,其中newValue返回目标元素变化之后的宽高以及目标元素相对父元素和页面左上角的坐标位置。
// xxx.ets
@Entry
@Component
struct AreaExample {
@State value: string = 'Text';
@State sizeValue: string = '';
build() {
Column() {
Text(this.value)
.backgroundColor(Color.Green).margin(30).fontSize(20)
.onClick(() => {
this.value = this.value + 'Text'
})
.onAreaChange((oldValue: Area, newValue: Area) => {
console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`)
this.sizeValue = JSON.stringify(newValue)
})
Text('new area is: \n' + this.sizeValue).margin({ right: 30, left: 30 })
}
.width('100%').height('100%').margin({ top: 30 })
}
}