1# Class (ComponentUtils) 2<!--Kit: ArkUI--> 3<!--Subsystem: ArkUI--> 4<!--Owner: @jiangtao92--> 5<!--Designer: @piggyguy--> 6<!--Tester: @songyanhong--> 7<!--Adviser: @HelloCrease--> 8 9提供获取组件绘制区域坐标和大小的能力。 10 11> **说明:** 12> 13> - 本模块首批接口从API version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 14> 15> - 本Class首批接口从API version 10开始支持。 16> 17> - 以下API需先使用UIContext中的[getComponentUtils()](./arkts-apis-uicontext-uicontext.md#getcomponentutils)方法获取到ComponentUtils对象,再通过该对象调用对应方法。 18 19## getRectangleById 20 21getRectangleById(id: string): componentUtils.ComponentInfo 22 23获取组件大小、位置、平移、缩放、旋转及仿射矩阵属性信息。 24 25> **说明:** 26> 27> 该接口需要在目标组件布局、完成以后获取目标组件区域大小信息,建议在[onAppear](./arkui-ts/ts-universal-events-show-hide.md#onappear)中使用该接口。 28 29**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 30 31**系统能力:** SystemCapability.ArkUI.ArkUI.Full 32 33**参数:** 34 35| 参数名 | 类型 | 必填 | 说明 | 36| ---- | ------ | ---- | --------- | 37| id | string | 是 | 组件唯一标识id。 | 38 39**返回值:** 40 41| 类型 | 说明 | 42| ------------------------------------------------------------ | ------------------------------------------------ | 43| [componentUtils.ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | 组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 | 44 45**错误码:** 46 47以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 48 49| 错误码ID | 错误信息 | 50| ------ | ------------------- | 51| 100001 | UI execution context not found. | 52 53**示例:** 54 55<!--code_no_check--> 56```ts 57import { ComponentUtils } from '@kit.ArkUI'; 58 59@Entry 60@Component 61struct Index { 62 @State message: string = 'Hello World'; 63 64 build() { 65 RelativeContainer() { 66 Text(this.message) 67 .id('HelloWorld') 68 .fontSize($r('app.float.page_text_font_size')) 69 .fontWeight(FontWeight.Bold) 70 .alignRules({ 71 center: { anchor: '__container__', align: VerticalAlign.Center }, 72 middle: { anchor: '__container__', align: HorizontalAlign.Center } 73 }) 74 .onClick(() => { 75 this.message = 'Welcome'; 76 let componentUtils: ComponentUtils = this.getUIContext().getComponentUtils(); 77 let modePosition = componentUtils.getRectangleById("HelloWorld"); 78 let width = modePosition.size.width; //获取组件的宽度 79 let height = modePosition.size.height; //获取组件的高度 80 let localOffsetX = modePosition.localOffset.x; // 获取组件相对于父组件的x轴偏移 81 let localOffsetY = modePosition.localOffset.y; // 获取组件相对于父组件的y轴偏移 82 console.info(`width: ${width}, height: ${height}, localOffsetX: ${localOffsetX}, localOffsetY: ${localOffsetY}`); 83 }) 84 } 85 .height('100%') 86 .width('100%') 87 } 88} 89``` 90