harmony 鸿蒙@ohos.measure (文本计算)

  • 2023-06-24
  • 浏览 (535)

@ohos.measure (文本计算)

本模块提供文本宽度、高度等相关计算。

说明

本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。

导入模块

import measure from '@ohos.measure'

measure.measureText

measureText(options: MeasureOptions): number

计算指定文本单行布局下的宽度。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名 类型 必填 说明
options MeasureOptions 被计算文本描述信息。

返回值:

类型 说明
number 文本宽度。
说明: 单位px。

示例:

import measure from '@ohos.measure'
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
  @State textWidth : number = measure.measureText({
    textContent: "Hello word",
    fontSize: '50px'
  })
  build() {
    Row() {
      Column() {
        Text("The width of 'Hello World': " + this.textWidth)
      }
      .width('100%')
    }
    .height('100%')
  }
}

measure.measureTextSize10+

measureTextSize(options: MeasureOptions): SizeOptions

计算指定文本单行布局下的宽度。

系统能力: SystemCapability.ArkUI.ArkUI.Full

参数:

参数名 类型 必填 说明
options MeasureOptions 被计算文本描述信息。

返回值:

类型 说明
SizeOption 返回文本所占布局宽度和高度。
说明: 文本宽度以及高度返回值单位均为px。

示例:

import measure from '@ohos.measure'
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
  textSize : SizeOptions = measure.measureTextSize({
    textContent: "Hello word",
    fontSize: '50px'
  })
  build() {
    Row() {
      Column() {
        Text("The width of 'Hello World': " + this.textSize.width)
        Text("The height of 'Hello World': " + this.textSize.height)
      }
      .width('100%')
    }
    .height('100%')
  }
}

MeasureOptions

被计算文本属性。

系统能力: SystemCapability.ArkUI.ArkUI.Full

名称 类型 必填 说明
textContent string 设置被计算文本内容。
constraintWidth10+ number | string | Resource 设置被计算文本布局宽度。
说明: 默认单位为vp
fontSize number | string | Resource 设置被计算文本字体大小,fontSize为number类型时,使用fp单位。
默认值:16fp。
说明: 不支持设置百分比字符串。
fontStyle number | FontStyle 设置被计算文本字体样式。
默认值:FontStyle.Normal
fontWeight number | string | FontWeight 设置被计算文本的字体粗细,number类型取值[100, 900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如”400”,以及”bold”、”bolder”、”lighter”、”regular”、”medium”,分别对应FontWeight中相应的枚举值。
默认值:FontWeight.Normal
fontFamily string | Resource 设置被计算文本字体列表。默认字体’HarmonyOS Sans’,且当前只支持这种字体。
letterSpacing number | string 设置被计算文本字符间距。
textAlign10+ number | TextAlign 设置被计算文本水平方向的对齐方式。
默认值:TextAlign.Start
overflow10+ number | TextOverflow 设置被计算文本超长时的截断方式。
maxLines10+ number 设置被计算文本最大行数。
lineHeight10+ number | string | Resource 设置被计算文本行高。
baselineOffset10+ number | string 设置被计算文本基线的偏移量。
默认值:0
textCase10+ number | TextCase 设置被计算文本大小写。
默认值:TextCase.Normal

你可能感兴趣的鸿蒙文章

harmony 鸿蒙接口

harmony 鸿蒙系统公共事件定义(待停用)

harmony 鸿蒙系统公共事件定义

harmony 鸿蒙开发说明

harmony 鸿蒙企业设备管理概述(仅对系统应用开放)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager模块)

harmony 鸿蒙@ohos.distributedBundle (分布式包管理)

harmony 鸿蒙@ohos.bundle (Bundle模块)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (企业设备管理扩展能力)

0  赞