鸿蒙NEXT版实战开发:UI框架-如何获取组件宽高和组件在屏幕上的位置

往期鸿蒙全套实战精彩文章必看内容:


如何获取组件宽高和组件在屏幕上的位置

方法一:可以使用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 }) 
  } 
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值