如何获取Text组件中文字的宽度?

如何获取Text组件中文字的宽度

阅读 444
1 个回答

可以使用 @ohos.measure 中的接口 MeasureText 计算指定文本单行布局下的宽度,具体可参考如下代码:

import { MeasureText } from '@kit.ArkUI' 
 
@Entry 
@Component 
struct Index { 
  @State textWidth: number = MeasureText.measureText({ 
    textContent: "Hello word", 
    fontSize: '50px' 
  }) 
 
  build() { 
    Row() { 
      Column() { 
        Text(`The width of 'Hello World': ${this.textWidth}`) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}

参考链接:

@ohos.measure (文本计算)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进