1# @ohos.graphics.text (文本模块)
2
3本模块允许开发者创建复杂的文本段落,包括多样的文本样式、段落样式、换行规则等,并最终将这些信息转换为能在屏幕上高效渲染的布局数据,本模块采用屏幕物理像素单位px。
4
5该模块提供以下创建复杂的文本段落的常用功能:
6
7- [TextStyle](#textstyle):文本样式,控制文本的字体类型、大小、间距等属性。
8- [FontCollection](#fontcollection):字体管理器,控制各种不同的字体。
9- [ParagraphStyle](#paragraphstyle):段落样式,控制整个段落的显示样式。
10- [Paragraph](#paragraph):段落,由ParagraphBuilder类调用[build()](#build)接口构建而成。
11- [ParagraphBuilder](#paragraphbuilder):段落生成器,控制生成不同的段落对象。
12- [TextLine](#textline):以行为单位的段落文本的载体,由段落类调用[getTextLines()](#gettextlines)接口获取。
13- [Run](#run):文本排版的渲染单元,由行文本类调用[getGlyphRuns()](#getglyphruns)接口获取。
14
15> **说明:**
16>
17> 本模块首批接口从API version 12开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
18
19## 导入模块
20
21```ts
22import { text } from '@kit.ArkGraphics2D';
23```
24
25## text.getSystemFontFullNamesByType<sup>14+</sup>
26
27getSystemFontFullNamesByType(fontType: SystemFontType): Promise&lt;Array&lt;string&gt;&gt;
28
29根据字体类型返回该类型对应的所有字体的字体名称,使用Promise异步回调。
30
31**系统能力:** SystemCapability.Graphics.Drawing
32
33**参数:**
34
35| 参数名 | 类型 | 必填 | 说明 |
36| - | - | - | - |
37| fontType | [SystemFontType](#systemfonttype14) | 是 | 指定的字体类型。 |
38
39**返回值:**
40
41| 类型 | 说明 |
42| - | - |
43| Promise&lt;Array&lt;string&gt;&gt; | Promise对象,返回相应字体类型的所有字体的字体名称。 |
44
45**错误码:**
46
47以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
48
49| 错误码ID | 错误信息 |
50| ------- | --------------------------------------------|
51| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. |
52
53**示例:**
54
55```ts
56import { text } from "@kit.ArkGraphics2D"
57import { BusinessError } from '@kit.BasicServicesKit';
58
59@Entry
60@Component
61struct Index {
62  build() {
63    Row() {
64      Column() {
65        Button("get font list")
66          .fontSize(30)
67          .fontWeight(FontWeight.Bold)
68          .width(300)
69          .height(80)
70          .onClick(() => {
71            let fontType:text.SystemFontType = text.SystemFontType.GENERIC
72            let promise = text.getSystemFontFullNamesByType(fontType)
73            promise.then((data) => {
74              console.info(`then font list size: ${data.length}`)
75              data.forEach((fontItem) => {
76                console.info(fontItem)
77              })
78            }).catch((error: BusinessError) => {
79              console.error(`Failed to get font fullNames by type, error: ${JSON.stringify(error)}`);
80            });
81          })
82      }
83      .width('100%')
84    }
85    .height('100%')
86  }
87}
88```
89
90## text.getFontDescriptorByFullName<sup>14+</sup>
91
92getFontDescriptorByFullName(fullName: string, fontType: SystemFontType): Promise&lt;FontDescriptor&gt;
93
94根据字体名称和字体类型获取对应的字体描述符,使用Promise异步回调。
95字体描述符是描述字体特征的一种数据结构,它包含了定义字体外观和属性的详细信息。
96
97**系统能力:** SystemCapability.Graphics.Drawing
98
99**参数:**
100
101| 参数名 | 类型 | 必填 | 说明 |
102| - | - | - | - |
103| fullName | string | 是 | 指定的字体名称。是从字体文件的name表中解析出来的一个字段。可以使用[getSystemFontFullNamesByType](#textgetsystemfontfullnamesbytype14)获取指定类型对应的所有字体的字体名称。 |
104| fontType | [SystemFontType](#systemfonttype14) | 是 | 指定的字体类型。 |
105
106**返回值:**
107
108| 类型 | 说明 |
109| - | - |
110| Promise&lt;[FontDescriptor](#fontdescriptor14)&gt; | Promise对象,返回指定的字体描述符。 |
111
112**错误码:**
113
114以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
115
116| 错误码ID | 错误信息 |
117| ------- | --------------------------------------------|
118| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. |
119
120**示例:**
121
122```ts
123import { text } from "@kit.ArkGraphics2D"
124import { BusinessError } from '@kit.BasicServicesKit';
125
126@Entry
127@Component
128struct Index {
129  build() {
130    Row() {
131      Column() {
132        Button("get fontDesciptor")
133          .fontSize(30)
134          .fontWeight(FontWeight.Bold)
135          .width(300)
136          .height(80)
137          .onClick(() => {
138            let fontType:text.SystemFontType = text.SystemFontType.GENERIC
139            let promise = text.getFontDescriptorByFullName("HarmonyOS Sans", fontType)
140            promise.then((fontdecriptor) => {
141              console.info(`desc: ${JSON.stringify(fontdecriptor)}`)
142            }).catch((error: BusinessError) => {
143              console.error(`Failed to get fontDescriptor by fullName, error: ${JSON.stringify(error)}`);
144            });
145          })
146      }
147      .width('100%')
148    }
149    .height('100%')
150  }
151}
152```
153
154## TextAlign
155
156文本对齐方式枚举。
157
158**系统能力:** SystemCapability.Graphics.Drawing
159
160| 名称        | 值   | 说明                                          |
161| --------- | ---- | ---------------------------------------------- |
162| LEFT      | 0    | 文本靠左对齐。                                  |
163| RIGHT     | 1    | 文本靠右对齐。                                  |
164| CENTER    | 2    | 文本居中对齐。                                  |
165| JUSTIFY   | 3    | 文本两侧对齐,对最后一行无效。                    |
166| START     | 4    | 基于文本的方向[TextDirection](#textdirection),文本靠开头方向对齐。 |
167| END       | 5    | 基于文本的方向[TextDirection](#textdirection),文本以结束方向对齐。 |
168
169## TextDirection
170
171文本排版方向枚举。
172
173**系统能力:** SystemCapability.Graphics.Drawing
174
175| 名称     | 值   | 说明              |
176| -------- | ---- | ---------------- |
177| RTL      | 0    | 文本从右到左排版。 |
178| LTR      | 1    | 文本从左到右排版。 |
179
180## BreakStrategy
181
182断行策略枚举。
183
184**系统能力:** SystemCapability.Graphics.Drawing
185
186| 名称          | 值   | 说明                                            |
187| ------------- | ---- | ---------------------------------------------- |
188| GREEDY        | 0    | 尽可能将当前行填满,不会自动添加连词符。           |
189| HIGH_QUALITY  | 1    | 布局优化,必要时会自动添加连词符。                |
190| BALANCED      | 2    | 保证一个段落的每一行的宽度相同,必要时会添加连词符。|
191
192## WordBreak
193
194断词策略枚举。
195
196**系统能力:** SystemCapability.Graphics.Drawing
197
198| 名称        | 值   | 说明                                                                                                                  |
199| ----------- | ---- | -------------------------------------------------------------------------------------------------------------------- |
200| NORMAL      | 0    | 默认的换行规则。依据各自语言的规则,允许在字间发生换行。                                                                  |
201| BREAK_ALL   | 1    | 对于 Non-CJK(非中文,日文,韩文)文本允许在任意字符内发生换行。该值适合包含一些非亚洲文本的亚洲文本,比如使连续的英文字符断行。|
202| BREAK_WORD  | 2    | 与`BREAK_ALL`基本相同,不同的地方在于它要求一个没有断行破发点的词必须保持为一个整体单位。                                   |
203
204## Decoration
205
206文本装饰线。
207
208**系统能力:** SystemCapability.Graphics.Drawing
209
210| 名称                      | 类型                                                  | 只读 | 可选 | 说明                                         |
211| ------------------------- | --------------------------------------------------- | ---- | ---- | -------------------------------------------- |
212| textDecoration            | [TextDecorationType](#textdecorationtype)           | 是   | 是   | 装饰线类型,默认为NONE。                       |
213| color                     | [common2D.Color](js-apis-graphics-common2D.md#color)| 是   | 是   | 装饰线颜色,默认为透明。                       |
214| decorationStyle           | [TextDecorationStyle](#textdecorationstyle)         | 是   | 是   | 装饰线样式,默认为SOLID。                      |
215| decorationThicknessScale  | number                                              | 是   | 是   | 装饰线粗细相对于默认值的比例,浮点数,默认为1.0。|
216
217## TextDecorationType
218
219装饰线类型枚举。
220
221**系统能力:** SystemCapability.Graphics.Drawing
222
223| 名称           | 值 | 说明        |
224| -------------- | - | ----------- |
225| NONE           | 0 | 装饰线不生效。|
226| UNDERLINE      | 1 | 下划线。      |
227| OVERLINE       | 2 | 上划线。     |
228| LINE_THROUGH   | 3 | 删除线。      |
229
230## TextDecorationStyle
231
232装饰线样式枚举。
233
234**系统能力:** SystemCapability.Graphics.Drawing
235
236| 名称   | 值 | 说明   |
237| ------ | - | ------ |
238| SOLID  | 0 | 实线。  |
239| DOUBLE | 1 | 双层线。|
240| DOTTED | 2 | 点状线。|
241| DASHED | 3 | 虚线。  |
242| WAVY   | 4 | 波浪线。|
243
244## FontWeight
245
246字重枚举。
247
248**系统能力:** SystemCapability.Graphics.Drawing
249
250| 名称  | 值 | 说明   |
251| ----- | - | ------- |
252| W100  | 0 | 100字重。|
253| W200  | 1 | 200字重。|
254| W300  | 2 | 300字重。|
255| W400  | 3 | 400字重。|
256| W500  | 4 | 500字重。|
257| W600  | 5 | 600字重。|
258| W700  | 6 | 700字重。|
259| W800  | 7 | 800字重。|
260| W900  | 8 | 900字重。|
261
262## FontWidth
263
264字体宽度的枚举。
265
266**系统能力:** SystemCapability.Graphics.Drawing
267
268| 名称             | 值 | 说明       |
269| ---------------- | - | ---------- |
270| ULTRA_CONDENSED  | 1 | 超窄字宽。  |
271| EXTRA_CONDENSED  | 2 | 特窄字宽。  |
272| CONDENSED        | 3 | 窄的字宽。  |
273| SEMI_CONDENSED   | 4 | 半窄字宽。  |
274| NORMAL           | 5 | 常规字宽。  |
275| SEMI_EXPANDED    | 6 | 半宽字宽。  |
276| EXPANDED         | 7 | 宽的字宽。  |
277| EXTRA_EXPANDED   | 8 | 特宽字宽。  |
278| ULTRA_EXPANDED   | 9 | 超宽的字宽。|
279
280## FontStyle
281
282字体样式枚举。
283
284**系统能力:** SystemCapability.Graphics.Drawing
285
286| 名称    | 值 | 说明                                                 |
287| ------- | - | ---------------------------------------------------- |
288| NORMAL  | 0 | 常规样式。                                            |
289| ITALIC  | 1 | 斜体,如果当前字体没有可用的斜体版本,会选用倾斜体替代。  |
290| OBLIQUE | 2 | 倾斜体,如果当前字体没有可用的倾斜体版本,会选用斜体替代。|
291
292## TextHeightBehavior
293
294文本高度修饰符模式枚举。
295
296**系统能力:** SystemCapability.Graphics.Drawing
297
298| 名称                  |  值 | 说明                                                  |
299| --------------------- | --- | ---------------------------------------------------- |
300| ALL                   | 0x0 | 高度修饰符设置为段落中第一行和最后一行都上升。            |
301| DISABLE_FIRST_ASCENT  | 0x1 | 高度修饰符设置为禁止段落中第一行上升。                   |
302| DISABLE_LAST_ASCENT   | 0x2 | 高度修饰符设置为禁止段落中最后一行上升。                 |
303| DISABLE_ALL           | 0x3 | 高度修饰符设置为段落中第一行和最后一行都不上升。          |
304
305## TextBaseline
306
307文本基线类型枚举。
308
309**系统能力:** SystemCapability.Graphics.Drawing
310
311| 名称        | 值 | 说明 |
312| ----------- | - | ---- |
313| ALPHABETIC  | 0 | 通常用于拉丁字母的文本基线对齐。|
314| IDEOGRAPHIC | 1 | 通常用于CJK(中文,日文,韩文)的文本基线对齐。|
315
316## EllipsisMode
317
318省略号类型枚举。
319
320EllipsisMode.STARTEllipsisMode.MIDDLE仅在单行超长文本生效。
321
322**系统能力:** SystemCapability.Graphics.Drawing
323
324| 名称   | 值 | 说明      |
325| ------ | - | --------- |
326| START  | 0 | 开头省略号。|
327| MIDDLE | 1 | 中间省略号。|
328| END    | 2 | 末尾省略号。|
329
330## TextShadow
331
332字体阴影。
333
334**系统能力:** SystemCapability.Graphics.Drawing
335
336| 名称          | 类型                                                 | 只读 | 可选 | 说明                               |
337| ------------- | ---------------------------------------------------- | --  | ---  | --------------------------------- |
338| color         | [common2D.Color](js-apis-graphics-common2D.md#color) | 是  |  是   | 字体阴影的颜色,默认为黑色Color(255, 0, 0, 0)。        |
339| point         | [common2D.Point](js-apis-graphics-common2D.md#point12) | 是  |  是   | 字体阴影基于当前文本的偏移位置,横、纵坐标要大于等于零。    |
340| blurRadius    | number                                               | 是  |  是   | 模糊半径,浮点数,默认为0.0px。       |
341
342## RectStyle
343
344矩形框样式。
345
346**系统能力:** SystemCapability.Graphics.Drawing
347
348| 名称               | 类型                                                 | 只读 | 可选 | 说明                                      |
349| -----------------  | ---------------------------------------------------- | --  | ---  | ---------------------------------------- |
350| color              | [common2D.Color](js-apis-graphics-common2D.md#color) | 是  |  否   | 矩形框的颜色。                 |
351| leftTopRadius      | number                                               | 是  |  否   | 矩形框的左上半径。       |
352| rightTopRadius     | number                                               | 是  |  否   | 矩形框的右上半径。       |
353| rightBottomRadius  | number                                               | 是  |  否   | 矩形框的右下半径。       |
354| leftBottomRadius   | number                                               | 是  |  否   | 矩形框的左下半径。       |
355
356## FontFeature
357
358文本字体特征。
359
360**系统能力:** SystemCapability.Graphics.Drawing
361
362| 名称      | 类型                                                 | 只读 | 可选 | 说明                                       |
363| --------- | ---------------------------------------------------- | --  | ---  | ----------------------------------------- |
364| name      | string                                               | 是  |  否   | 字体特征键值对中关键字所标识的字符串。       |
365| value     | number                                               | 是  |  否   | 字体特征键值对的值。                        |
366
367## FontVariation
368
369可变字体属性。
370
371**系统能力:** SystemCapability.Graphics.Drawing
372
373| 名称      | 类型                                                 | 只读 | 可选 | 说明                                       |
374| --------- | ---------------------------------------------------- | --  | ---  | ----------------------------------------- |
375| axis      | string                                               | 是  |  否   | 可变字体属性键值对中关键字所标识的字符串。       |
376| value     | number                                               | 是  |  否   | 可变字体属性键值对的值。                        |
377
378## TextStyle
379
380文本样式。
381
382**系统能力:** SystemCapability.Graphics.Drawing
383
384| 名称                      | 类型                                     | 只读 | 可选 | 说明                                                   |
385| ------------- | ---------------------------------------------------- | -- | -- | --------------------------------------------------------- |
386| decoration    | [Decoration](#decoration)                            | 是 | 是 | 装饰线置,默认初始的Decoration。             |
387| color         | [common2D.Color](js-apis-graphics-common2D.md#color) | 是 | 是 | 字体色,默认为白色。                         |
388| fontWeight    | [FontWeight](#fontweight)                            | 是 | 是 | 字重,默认为W400。 目前只有系统默认字体支持字重的调节,其他字体设置字重值小于semi-bold(即W600)时字体粗细无变化,当设置字重值大于等于semi-bold(即W600)时可能会触发伪加粗效果。                         |
389| fontStyle     | [FontStyle](#fontstyle)                              | 是 | 是 | 字体样式,默认为常规样式。                          |
390| baseline      | [TextBaseline](#textbaseline)                        | 是 | 是 | 文本基线型,默认为ALPHABETIC。               |
391| fontFamilies  | Array\<string>                                       | 是 | 是 | 字体族名称列表,默认为系统字体。                    |
392| fontSize      | number                                               | 是 | 是 | 字体大小,浮点数,默认为14.0,单位为px。  |
393| letterSpacing | number                                               | 是 | 是 | 字符间距,正数拉开字符距离,若是负数则拉近字符距离,浮点数,默认为0.0,单位为物理像素px。|
394| wordSpacing   | number                                               | 是 | 是 | 单词间距,浮点数,默认为0.0,单位为px。                 |
395| heightScale   | number                                               | 是 | 是 | 行高缩放倍数,浮点数,默认为1.0,heightOnly为true时生效。              |
396| heightOnly    | boolean                                              | 是 | 是 | true表示根据字体大小和heightScale设置文本框的高度,false表示根据行高和行距,默认为false。|
397| halfLeading   | boolean                                              | 是 | 是 | true表示将行间距平分至行的顶部与底部,false则不平分,默认为false。|
398| ellipsis      | string                                               | 是 | 是 | 省略号样式,表示省略号生效后使用该字段值替换省略号部分。       |
399| ellipsisMode  | [EllipsisMode](#ellipsismode)                        | 是 | 是 | 省略号类型,默认为END,行尾省略号。                        |
400| locale        | string                                               | 是 | 是 | 语言类型,如字段为'en'代表英文,'zh-Hans'代表简体中文,'zh-Hant'代表繁体中文。具体请参照ISO 639-1规范,默认为空字符串。|
401| baselineShift | number                                               | 是 | 是 | 文本下划线的偏移距离,浮点数,默认为0.0px。                 |
402| fontFeatures  | Array\<[FontFeature](#fontfeature)>                  | 是 | 是 | 文本字体特征数组。|
403| fontVariations| Array\<[FontVariation](#fontvariation)>              | 是 | 是 | 可变字体属性数组。|
404| textShadows   | Array\<[TextShadow](#textshadow)>                    | 是 | 是 | 文本字体阴影数组。|
405| backgroundRect| [RectStyle](#rectstyle)                              | 是 | 是 | 文本矩形框样式。|
406
407## StrutStyle
408
409支柱样式,用于控制绘制文本的行间距、基线对齐方式以及其他与行高相关的属性,默认不开启。
410
411**系统能力:** SystemCapability.Graphics.Drawing
412
413| 名称                      | 类型                                       | 只读 | 可选 | 说明                                                                 |
414| -------------  | ---------------------------------------------------- | ---- | -- | --------------------------------------------------------------------- |
415| fontFamilies   | Array\<string>                                       | 是   | 是 | 字体类型,默认为系统字体。                                               |
416| fontStyle      | [FontStyle](#fontstyle)                              | 是   | 是 | 字体样式,默认为常规样式。                                               |
417| fontWidth      | [FontWidth](#fontwidth)                              | 是   | 是 | 字体宽度,默认为NORMAL。                                                |
418| fontWeight     | [FontWeight](#fontweight)                            | 是   | 是 | 字重,默认为W400。目前只有系统默认字体支持字重的调节,其他字体设置字重值小于semi-bold(即W600)时字体粗细无变化,当设置字重值大于等于semi-bold(即W600)时可能会触发伪加粗效果。                             |
419| fontSize       | number                                               | 是   | 是 | 字体大小,浮点数,默认为14.0,单位为物理像素px。                             |
420| height         | number                                               | 是   | 是 | 行高缩放倍数,浮点数,默认为1.0。                                         |
421| leading        | number                                               | 是   | 是 | 以自定义行距应用于支柱的行距,浮点数,默认为-1.0。                          |
422| forceHeight    | boolean                                              | 是   | 是 | 是否所有行都将使用支柱的高度,true表示使用,false表示不使用,默认为false。     |
423| enabled        | boolean                                              | 是   | 是 | 是否启用支柱样式,true表示使用,false表示不使用,默认为false。              |
424| heightOverride | boolean                                              | 是   | 是 | 是否覆盖高度,true表示覆盖,false表示不覆盖,默认为false。                  |
425| halfLeading    | boolean                                              | 是   | 是 | true表示将行间距平分至行的顶部与底部,false则不平分,默认为false。           |
426
427## FontDescriptor<sup>14+</sup>
428
429字体描述符信息。
430
431**系统能力**:SystemCapability.Graphics.Drawing
432
433| 名称 | 类型 | 只读 | 可选 | 说明 |
434| - | - | -  | - | - |
435| path | string | 否 | 是 | 字体绝对路径,可取任意值,默认值为空字符串。 |
436| postScriptName | string | 否 | 是 | 字体唯一标识名称,可取任意值,默认值为空字符串。 |
437| fullName | string | 否 | 是 | 字体名称,可取任意值,默认值为空字符串。 |
438| fontFamily | string | 否 | 是 | 字体家族,可取任意值,默认值为空字符串。 |
439| fontSubfamily | string | 否 | 是 | 子字体家族,可取任意值,默认值为空字符串。 |
440| weight | [FontWeight](#fontweight) | 否 | 是 | 字体字重,默认值为FontWeight.W100的取值,即0。 |
441| width | number | 否 | 是 | 字体宽度,取值范围是1-9整数,默认值为0。 |
442| italic | number | 否 | 是 | 是否是斜体字体,0表示非斜体,1表示斜体字体,默认值为0。 |
443| monoSpace | boolean | 否 | 是 | 是否是等宽字体,true表示等宽字体,false表示非等宽字体,默认值为false。 |
444| symbolic | boolean | 否 | 是 | 是否支持符号,true表示支持,false表示不支持,默认值为false。 |
445
446## FontCollection
447
448字体管理器。
449
450### getGlobalInstance
451
452static getGlobalInstance(): FontCollection
453
454获取应用全局FontCollection的实例。
455
456**系统能力**:SystemCapability.Graphics.Drawing
457
458**返回值:**
459
460| 类型   | 说明                |
461| ------ | ------------------ |
462| [FontCollection](#fontcollection) | FontCollection对象。|
463
464**示例:**
465
466```ts
467import { text } from "@kit.ArkGraphics2D"
468
469function textFunc() {
470  let fontCollection = text.FontCollection.getGlobalInstance();
471}
472
473@Entry
474@Component
475struct Index {
476  fun: Function = textFunc;
477  build() {
478    Column() {
479      Button().onClick(() => {
480        this.fun();
481      })
482    }
483  }
484}
485```
486
487### loadFontSync
488
489loadFontSync(name: string, path: string | Resource): void
490
491同步接口,将路径对应的文件,以name作为使用的别名,加载成自定义字体。其中参数name对应的值需要在[TextStyle](#textstyle)中的fontFamilies属性配置,才能显示自定义的字体效果。支持的字体文件格式包含:ttf、otf。
492
493**系统能力**:SystemCapability.Graphics.Drawing
494
495**参数:**
496
497| 参数名 | 类型               | 必填 | 说明                              |
498| ----- | ------------------ | ---- | --------------------------------------------------------------------------------- |
499| name  | string             | 是   | 加载成字体后,调用该字体所使用的命名。                                                |
500| path  | string \| [Resource](../apis-arkui/arkui-ts/ts-types.md#resource) | 是   | 需要导入的字体文件的路径,应为 "file:// + 字体文件绝对路径" 或 "rawfile/目录or文件名"。 |
501
502**示例:**
503
504```ts
505import { text } from "@kit.ArkGraphics2D"
506
507let fontCollection: text.FontCollection = new text.FontCollection();
508
509@Entry
510@Component
511struct RenderTest {
512  LoadFontSyncTest() {
513    fontCollection.loadFontSync('Clock_01', 'file:///system/fonts/HarmonyClock_01.ttf')
514    let fontFamilies: Array<string> = ["Clock_01"]
515    let myTextStyle: text.TextStyle = {
516      fontFamilies: fontFamilies
517    };
518    let myParagraphStyle: text.ParagraphStyle = {
519      textStyle: myTextStyle,
520    }
521    let paragraphBuilder: text.ParagraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
522
523    let textData = "测试 loadFontSync 加载字体HarmonyClock_01.ttf";
524    paragraphBuilder.addText(textData);
525    let paragraph: text.Paragraph = paragraphBuilder.build();
526    paragraph.layoutSync(600);
527  }
528
529  aboutToAppear() {
530    this.LoadFontSyncTest();
531  }
532
533  build() {
534  }
535}
536```
537
538### clearCaches
539
540clearCaches(): void
541
542清理字体排版缓存(字体排版缓存本身设有内存上限和清理机制,所占内存有限,如无内存要求,不建议清理)。
543
544**系统能力**:SystemCapability.Graphics.Drawing
545
546**示例:**
547
548```ts
549import { text } from "@kit.ArkGraphics2D"
550
551@Entry
552@Component
553struct Index {
554  build() {
555    Column() {
556      Button().onClick(() => {
557        text.FontCollection.getGlobalInstance().clearCaches();
558      })
559    }
560  }
561}
562```
563
564## ParagraphStyle
565
566段落样式。
567
568**系统能力:** SystemCapability.Graphics.Drawing
569
570| 名称                 | 类型                                        | 只读 | 可选 | 说明                                          |
571| -------------------- | ------------------------------------------ | ---- | ---- | -------------------------------------------- |
572| textStyle            | [TextStyle](#textstyle)                    | 是   | 是   | 作用于整个段落的文本样式,默认为初始的文本样式。|
573| textDirection        | [TextDirection](#textdirection)            | 是   | 是   | 文本方向,默认为LTR。                          |
574| align                | [TextAlign](#textalign)                    | 是   | 是   | 文本对齐方式,默认为START。当与制表符对齐方式同时配置时(即同时配置tab属性时),制表符对齐方式不生效。|
575| wordBreak            | [WordBreak](#wordbreak)                    | 是   | 是   | 断词类型,默认为BREAK_WORD。                    |
576| maxLines             | number                                     | 是   | 是   | 最大行数限制,整数,默认为1e9。                  |
577| breakStrategy        | [BreakStrategy](#breakstrategy)            | 是   | 是   | 断行策略,默认为GREEDY。                        |
578| strutStyle           | [StrutStyle](#strutstyle)                  | 是   | 是   | 支柱样式,默认为初始的StrutStyle。               |
579| textHeightBehavior   | [TextHeightBehavior](#textheightbehavior)  | 是   | 是   | 文本高度修饰符模式,默认为ALL。                              |
580
581
582## PlaceholderAlignment
583
584占位符相对于周围文本的纵向的对齐方式。
585
586**系统能力:** SystemCapability.Graphics.Drawing
587
588| 名称                | 值 | 说明                   |
589| ------------------- | - | ---------------------- |
590| OFFSET_AT_BASELINE  | 0 | 基线与文本基线对齐。     |
591| ABOVE_BASELINE      | 1 | 将底部与文本基线对齐。   |
592| BELOW_BASELINE      | 2 | 将顶部与文本基线对齐。   |
593| TOP_OF_ROW_BOX      | 3 | 将顶部与文本顶部对齐。   |
594| BOTTOM_OF_ROW_BOX   | 4 | 将底部与文本底部对齐。   |
595| CENTER_OF_ROW_BOX   | 5 | 中线与文本的中线位置对齐。|
596
597![zh-ch_image_PlaceholderAlignment.png](figures/zh-ch_image_PlaceholderAlignment.png)
598
599> **说明:**
600>
601> 示意图只展示了后三种,前三种与其类似,只不过比较位置变成了文本基线位置,即绿色线条部分。
602>
603>![zh-ch_image_Baseline.png](figures/zh-ch_image_Baseline.png)
604
605## PlaceholderSpan
606
607描述占位符样式的载体。
608
609**系统能力:** SystemCapability.Graphics.Drawing
610
611| 名称           | 类型                                           | 只读 | 可选 | 说明                         |
612| -------------- | --------------------------------------------- | ---- | --- | --------------------------- |
613| width          | number                                        | 是   | 否   | 占位符的宽度,浮点数,单位为物理像素px。|
614| height         | number                                        | 是   | 否   | 占位符的高度,浮点数,单位为物理像素px。|
615| align          | [PlaceholderAlignment](#placeholderalignment) | 是   | 否   | 相对于周围文本的纵向的对齐方式。|
616| baseline       | [TextBaseline](#textbaseline)                 | 是   | 否   | 基线类型。                   |
617| baselineOffset | number                                        | 是   | 否   | 基线偏移量,浮点数,单位为物理像素px。  |
618
619## Range
620
621描述一个左闭右开的区间。
622
623**系统能力:** SystemCapability.Graphics.Drawing
624
625| 名称   | 类型   | 只读 | 可选 | 说明            |
626| ----- | ------ | ---- | --- | --------------- |
627| start | number | 是   | 否   | 区间左侧端点索引,整数。|
628| end   | number | 是   | 否   | 区间右侧端点索引,整数。|
629
630## Paragraph
631
632保存着文本内容以及样式的载体,可以进行排版绘制等操作。
633
634下列API示例中都需先使用[ParagraphBuilder](#paragraphbuilder)类的[build()](#build)接口获取到Paragraph对象实例,再通过此实例调用对应方法。
635
636### layoutSync
637
638layoutSync(width: number): void
639
640进行排版,计算所有字形的位置。
641
642**系统能力**:SystemCapability.Graphics.Drawing
643
644**参数:**
645
646| 参数名 | 类型   | 必填 | 说明           |
647| ----- | ------ | ---- | -------------- |
648| width | number | 是   | 单行的最大宽度,浮点数,单位为物理像素px。|
649
650**示例:**
651
652```ts
653paragraph.layoutSync(100);
654```
655
656### paint
657
658paint(canvas: drawing.Canvas, x: number, y: number): void
659
660在画布上以坐标点 (x, y) 为左上角位置绘制文本。
661
662**系统能力**:SystemCapability.Graphics.Drawing
663
664**参数:**
665
666| 参数名 | 类型                                                  | 必填 | 说明                    |
667| ------ | ---------------------------------------------------- | ---- | ---------------------- |
668| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | 是   | 绘制的目标画布。         |
669|    x   | number                                               | 是   | 绘制的左上角位置的横坐标,浮点数。|
670|    y   | number                                               | 是   | 绘制的左上角位置的纵坐标,浮点数。|
671
672**示例:**
673
674```ts
675const color: ArrayBuffer = new ArrayBuffer(160000);
676let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } }
677let pixelMap: image.PixelMap = image.createPixelMapSync(color, opts);
678let canvas = new drawing.Canvas(pixelMap);
679paragraph.paint(canvas, 0, 0);
680```
681
682### paintOnPath
683
684paintOnPath(canvas: drawing.Canvas, path: drawing.Path, hOffset: number, vOffset: number): void
685
686在画布上沿路径绘制文本。
687
688**系统能力**:SystemCapability.Graphics.Drawing
689
690**参数:**
691
692| 参数名 | 类型                                                  | 必填 | 说明                    |
693| ------ | ---------------------------------------------------- | ---- | ---------------------- |
694| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | 是   | 绘制的目标画布。         |
695| path | [drawing.Path](js-apis-graphics-drawing.md#path) | 是   | 确认文字位置的路径。         |
696|    hOffset   | number                                               | 是   | 沿路径方向偏置,从路径起点向前为正,向后为负。|
697|    vOffset   | number                                               | 是   | 沿路径垂直方向偏置,沿路径方向左侧为负,右侧为正。|
698
699**示例:**
700
701```ts
702const color: ArrayBuffer = new ArrayBuffer(160000);
703let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } }
704let pixelMap: image.PixelMap = image.createPixelMapSync(color, opts);
705let canvas = new drawing.Canvas(pixelMap);
706let path = new drawing.Path();
707path.arcTo(20, 20, 180, 180, 180, 90);
708paragraph.paintOnPath(canvas, path, 0, 0);
709```
710
711### getMaxWidth
712
713getMaxWidth(): number
714
715获取文本最大的行宽。
716
717**系统能力**:SystemCapability.Graphics.Drawing
718
719**返回值:**
720
721| 类型   | 说明       |
722| ------ | --------- |
723| number | 最大的行宽,浮点数,单位为物理像素px。|
724
725**示例:**
726
727```ts
728let maxWidth = paragraph.getMaxWidth();
729```
730
731### getHeight
732
733getHeight(): number
734
735获取文本总高度。
736
737**系统能力**:SystemCapability.Graphics.Drawing
738
739**返回值:**
740
741| 类型   | 说明   |
742| ------ | ----- |
743| number | 总高度,浮点数,单位为物理像素px。|
744
745**示例:**
746
747```ts
748let height = paragraph.getHeight();
749```
750
751### getLongestLine
752
753getLongestLine(): number
754
755获取文本最长一行的宽度。
756
757**系统能力**:SystemCapability.Graphics.Drawing
758
759**返回值:**
760
761| 类型   | 说明           |
762| ------ | ------------- |
763| number | 最长一行的宽度,浮点数,单位为物理像素px。|
764
765**示例:**
766
767```ts
768let longestLine = paragraph.getLongestLine();
769```
770
771### getLongestLineWithIndent<sup>13+</sup>
772
773getLongestLineWithIndent(): number
774
775获取文本最长一行的宽度(该宽度包含当前行缩进的宽度),建议实际使用时将返回值向上取整。当文本内容为空时,返回0。
776
777**系统能力**:SystemCapability.Graphics.Drawing
778
779**返回值:**
780
781| 类型   | 说明           |
782| ------ | ------------- |
783| number | 最长一行的宽度(该宽度包含当前行缩进的宽度),浮点数,单位为物理像素px。|
784
785**示例:**
786
787```ts
788let longestLineWithIndent = paragraph.getLongestLineWithIndent();
789```
790
791### getMinIntrinsicWidth
792
793getMinIntrinsicWidth(): number
794
795获取该段落所占水平空间的最小固有宽度。
796
797**系统能力**:SystemCapability.Graphics.Drawing
798
799**返回值:**
800
801| 类型   | 说明                           |
802| ------ | ----------------------------- |
803| number | 该段落所占水平空间的最小固有宽度,浮点数,单位为物理像素px。|
804
805**示例:**
806
807```ts
808let minIntrinsicWidth = paragraph.getMinIntrinsicWidth();
809```
810
811### getMaxIntrinsicWidth
812
813getMaxIntrinsicWidth(): number
814
815获取该段落所占水平空间的最大固有宽度。
816
817**系统能力**:SystemCapability.Graphics.Drawing
818
819**返回值:**
820
821| 类型   | 说明                           |
822| ------ | ----------------------------- |
823| number | 该段落所占水平空间的最大固有宽度,浮点数,单位为物理像素px。|
824
825**示例:**
826
827```ts
828let maxIntrinsicWidth = paragraph.getMaxIntrinsicWidth();
829```
830
831### getAlphabeticBaseline
832
833getAlphabeticBaseline(): number
834
835获取拉丁字母下的基线位置。
836
837**系统能力**:SystemCapability.Graphics.Drawing
838
839**返回值:**
840
841| 类型   | 说明                |
842| ------ | ------------------ |
843| number | 拉丁字母下的基线位置,浮点数,单位为物理像素px。|
844
845**示例:**
846
847```ts
848let alphabeticBaseline = paragraph.getAlphabeticBaseline();
849```
850
851### getIdeographicBaseline
852
853getIdeographicBaseline(): number
854
855获取表意字(如CJK(中文,日文,韩文))下的基线位置。
856
857**系统能力**:SystemCapability.Graphics.Drawing
858
859**返回值:**
860
861| 类型   | 说明                  |
862| ------ | -------------------- |
863| number | 获取表意字下的基线位置,浮点数,单位为物理像素px。|
864
865**示例:**
866
867```ts
868let ideographicBaseline = paragraph.getIdeographicBaseline();
869```
870
871### getRectsForRange
872
873getRectsForRange(range: Range, widthStyle: RectWidthStyle, heightStyle: RectHeightStyle): Array\<TextBox>
874
875获取给定的矩形区域宽度以及矩形区域高度的规格下,文本中该区间范围内的字符的所占的矩形区域。
876
877**系统能力**:SystemCapability.Graphics.Drawing
878
879**参数:**
880
881| 参数名      | 类型                                 | 必填 | 说明                     |
882| ----------- | ----------------------------------- | ---- | ------------------------ |
883| range       | [Range](#range)                     | 是   | 需要获取的区域的文本区间。  |
884| widthStyle  | [RectWidthStyle](#rectwidthstyle)   | 是   | 返回的矩形区域的宽度的规格。|
885| heightStyle | [RectHeightStyle](#rectheightstyle) | 是   | 返回的矩形区域的高度的规格。|
886
887**返回值:**
888
889| 类型                         | 说明        |
890| --------------------------- | ----------- |
891| Array\<[TextBox](#textbox)> | 矩形区域数组。|
892
893**示例:**
894
895```ts
896let range: text.Range = { start: 0, end: 1};
897let rects = paragraph.getRectsForRange(range, text.RectWidthStyle.TIGHT, text.RectHeightStyle.TIGHT);
898```
899
900### getRectsForPlaceholders
901
902getRectsForPlaceholders(): Array\<TextBox>
903
904获取文本中所有占位符所占的矩形区域。
905
906**系统能力**:SystemCapability.Graphics.Drawing
907
908**返回值:**
909
910| 类型                         | 说明        |
911| --------------------------- | ----------- |
912| Array\<[TextBox](#textbox)> | 矩形区域数组。|
913
914**示例:**
915
916```ts
917let placeholderRects = paragraph.getRectsForPlaceholders();
918```
919
920### getGlyphPositionAtCoordinate
921
922getGlyphPositionAtCoordinate(x: number, y: number): PositionWithAffinity
923
924获取较为接近给定坐标的字形的位置信息。
925
926**系统能力**:SystemCapability.Graphics.Drawing
927
928**参数:**
929
930| 参数名 | 类型   | 必填 | 说明   |
931| ----- | ------ | ---- | ------ |
932| x     | number | 是   | 横坐标,浮点数。|
933| y     | number | 是   | 纵坐标,浮点数。|
934
935**返回值:**
936
937| 类型                                          | 说明        |
938| --------------------------------------------- | ----------- |
939| [PositionWithAffinity](#positionwithaffinity) | 字形位置信息。|
940
941**示例:**
942
943```ts
944let positionWithAffinity = paragraph.getGlyphPositionAtCoordinate(0, 0);
945```
946
947### getWordBoundary
948
949getWordBoundary(offset: number): Range
950
951返回给定的 offset 的字形所处的单词的索引区间。
952
953**系统能力**:SystemCapability.Graphics.Drawing
954
955**参数:**
956
957| 参数名 | 类型    | 必填 | 说明        |
958| ------ | ------ | ---- | ----------- |
959| offset | number | 是   | 字形的偏移量,整数。|
960
961**返回值:**
962
963| 类型            | 说明            |
964| --------------- | -------------- |
965| [Range](#range) | 单词的索引区间。|
966
967**示例:**
968
969```ts
970let wordRange = paragraph.getWordBoundary(0);
971```
972
973### getLineCount
974
975getLineCount(): number
976
977返回文本行数量。
978
979**系统能力**:SystemCapability.Graphics.Drawing
980
981**返回值:**
982
983| 类型   | 说明       |
984| ------ | --------- |
985| number | 文本行数量,整数。|
986
987**示例:**
988
989```ts
990let lineCount = paragraph.getLineCount();
991```
992
993### getLineHeight
994
995getLineHeight(line: number): number
996
997返回指定行索引的行高。
998
999**系统能力**:SystemCapability.Graphics.Drawing
1000
1001**参数:**
1002
1003| 参数名 | 类型   | 必填 | 说明      |
1004| ----- | ------ | ---- | --------- |
1005| line  | number | 是   | 文本行索引,整数。|
1006
1007**返回值:**
1008
1009| 类型   | 说明  |
1010| ------ | ---- |
1011| number | 行高。|
1012
1013**示例:**
1014
1015```ts
1016let lineHeight = paragraph.getLineHeight(0);
1017```
1018
1019### getLineWidth
1020
1021getLineWidth(line: number): number
1022
1023返回指定行索引的行宽。
1024
1025**系统能力**:SystemCapability.Graphics.Drawing
1026
1027**参数:**
1028
1029| 参数名 | 类型   | 必填 | 说明      |
1030| ----- | ------ | ---- | --------- |
1031| line  | number | 是   | 文本行索引,整数。|
1032
1033**返回值:**
1034
1035| 类型   | 说明  |
1036| ------ | ---- |
1037| number | 行宽。|
1038
1039**示例:**
1040
1041```ts
1042let lineWidth = paragraph.getLineWidth(0);
1043```
1044
1045### didExceedMaxLines
1046
1047didExceedMaxLines(): boolean
1048
1049返回段落是否超过最大行限制。
1050
1051**系统能力**:SystemCapability.Graphics.Drawing
1052
1053**返回值:**
1054
1055| 类型    | 说明                                                      |
1056| ------- | -------------------------------------------------------- |
1057| boolean | true表示段落超出了最大行限制,false则表示没有超出最大行限制。 |
1058
1059**示例:**
1060
1061```ts
1062let didExceed = paragraph.didExceedMaxLines();
1063```
1064
1065### getTextLines
1066
1067getTextLines(): Array\<TextLine>
1068
1069返回所有的文本行载体。
1070
1071**系统能力**:SystemCapability.Graphics.Drawing
1072
1073**返回值:**
1074
1075| 类型                          | 说明          |
1076| ----------------------------- | ------------- |
1077| Array\<[TextLine](#textline)> | 文本行载体数组。|
1078
1079**示例:**
1080
1081```ts
1082let lines = paragraph.getTextLines();
1083```
1084
1085### getActualTextRange
1086
1087getActualTextRange(lineNumber: number, includeSpaces: boolean): Range
1088
1089获取指定行号上的实际可见文本范围,这不包括由于文本溢出而显示的省略号。
1090
1091**系统能力**:SystemCapability.Graphics.Drawing
1092
1093**参数:**
1094
1095| 参数名 | 类型   | 必填 | 说明      |
1096| ----- | ------ | ---- | --------- |
1097| lineNumber  | number | 是   | 要获取文本范围的行号,行号从0开始。|
1098| includeSpaces  | boolean | 是   | 指示是否应包含空白字符。true表示包含空白字符,false表示不包含空白字符。|
1099
1100**返回值:**
1101
1102| 类型             | 说明                                              |
1103| ---------------- | ------------------------------------------------ |
1104| [Range](#range)  | 表明了对应行数的实际文本范围。                               |
1105
1106**示例:**
1107
1108```ts
1109let rang = paragraph.getActualTextRange(0, true);
1110```
1111
1112
1113### getLineMetrics
1114
1115getLineMetrics(): Array\<LineMetrics>
1116
1117获取文本行的行度量数组。
1118
1119**系统能力**:SystemCapability.Graphics.Drawing
1120
1121**返回值:**
1122
1123| 类型                          | 说明          |
1124| ----------------------------- | ------------- |
1125| Array\<[LineMetrics](#linemetrics)> | 文本行的行度量数组。|
1126
1127**示例:**
1128
1129```ts
1130let arrLineMetrc =  paragraph.getLineMetrics();
1131```
1132
1133### getLineMetrics
1134
1135getLineMetrics(lineNumber: number): LineMetrics | undefined
1136
1137获取特定行号的行度量信息。
1138
1139**系统能力**:SystemCapability.Graphics.Drawing
1140
1141**参数:**
1142
1143| 参数名 | 类型   | 必填 | 说明      |
1144| ----- | ------ | ---- | --------- |
1145| lineNumber  | number | 是   | 要查询度量信息的行的编号, 行号从0开始。|
1146
1147**返回值:**
1148
1149| 类型             | 说明                                              |
1150| ---------------- | ------------------------------------------------ |
1151| [LineMetrics](#linemetrics) | 如果指定的行号有效且度量信息存在,则返回一个包含该行度量数据的LineMetrics对象;如果行号无效或无法获取度量信息,则返回undefined。                  |
1152
1153**示例:**
1154
1155```ts
1156let lineMetrics =  paragraph.getLineMetrics(0);
1157```
1158
1159## RunMetrics
1160
1161描述文本行中连续文本块的布局信息和度量数据。
1162
1163**系统能力:** SystemCapability.Graphics.Drawing
1164
1165| 名称      | 类型                                                | 只读 | 可选 | 说明        |
1166| --------- | -------------------------------------------------- | ---- | ---- | ----------- |
1167| textStyle | [TextStyle](#textstyle)                             | 是   | 否   | 字体的样式信息。|
1168| fontMetrics | [drawing.FontMetrics](js-apis-graphics-drawing.md#fontmetrics)| 是   | 否   | 字体度量信息。    |
1169
1170## LineMetrics
1171
1172用于描述文本布局中单行文字的度量信息。
1173
1174**系统能力:** SystemCapability.Graphics.Drawing
1175
1176| 名称      | 类型                                                | 只读 | 可选 | 说明        |
1177| --------- | -------------------------------------------------- | ---- | ---- | ----------- |
1178| startIndex | number                                            | 是   | 否   | 文本缓冲区中该行开始的索引位置。|
1179| endIndex   | number                                            | 是   | 否   | 文本缓冲区中该行结束的索引位置。|
1180| ascent     | number                                            | 是   | 否   | 文字上升高度,即从基线到字符顶部的距离。|
1181| descent    | number                                            | 是   | 否   | 文字下降高度,即从基线到字符底部的距离。|
1182| height     | number                                            | 是   | 否   | 当前行的高度,计算方式为 `Math.round(ascent + descent)`|
1183| width      | number                                            | 是   | 否   | 行的宽度。                      |
1184| left       | number                        | 是   | 否   | 行的左边缘位置。右边缘可通过 `left+width` 计算得出。|
1185| baseline   | number                        | 是   | 否   | 该行基线相对于段落顶部的 Y 坐标位置。|
1186| lineNumber   | number                        | 是   | 否   | 行号,从0开始计数。|
1187| topHeight   | number                        | 是   | 否   | 从顶部到当前行的高度。|
1188| runMetrics   | Map<number, [RunMetrics](#runmetrics)>                        | 是   | 否   | 文本索引范围与关联的字体度量信息之间的映射。|
1189
1190## TextBox
1191
1192文本矩形区域。
1193
1194**系统能力:** SystemCapability.Graphics.Drawing
1195
1196| 名称      | 类型                                                | 只读 | 可选 | 说明        |
1197| --------- | -------------------------------------------------- | ---- | ---- | ----------- |
1198| rect      | [common2D.Rect](js-apis-graphics-common2D.md#rect) | 是   | 否   | 矩形区域信息。|
1199| direction | [TextDirection](#textdirection)                    | 是   | 否   | 文本方向。    |
1200
1201## PositionWithAffinity
1202
1203位置以及亲和度。
1204
1205**系统能力:** SystemCapability.Graphics.Drawing
1206
1207| 名称      | 类型                   | 只读 | 可选 | 说明                      |
1208| --------- | --------------------- | ---- | ---- | ------------------------ |
1209| position  | number                | 是   | 否   | 字形相对于段落的索引,整数。  |
1210| affinity  | [Affinity](#affinity) | 是   | 否   | 位置亲和度。               |
1211
1212## RectWidthStyle
1213
1214矩形区域宽度规格枚举。
1215
1216**系统能力:** SystemCapability.Graphics.Drawing
1217
1218| 名称  | 值 | 说明                                   |
1219| ----- | - | -------------------------------------- |
1220| TIGHT | 0 | 不设置letterSpacing时,与字形紧贴,否则包含letterSpacing。                            |
1221| MAX   | 1 | 扩展宽度,以匹配所有行上最宽矩形的位置。   |
1222
1223## RectHeightStyle
1224
1225矩形区域高度规格枚举。
1226
1227**系统能力:** SystemCapability.Graphics.Drawing
1228
1229| 名称                      | 值 | 说明                                           |
1230| ------------------------- | - | ---------------------------------------------- |
1231| TIGHT                     | 0 | 与字形紧贴。                                    |
1232| MAX                       | 1 | 扩展高度,以匹配所有行上最高矩形的位置。           |
1233| INCLUDE_LINE_SPACE_MIDDLE | 2 | 每个矩形的顶部和底部将覆盖行上方和行下方的一半空间。|
1234| INCLUDE_LINE_SPACE_TOP    | 3 | 行间距将被添加到矩形的顶部。                      |
1235| INCLUDE_LINE_SPACE_BOTTOM | 4 | 行间距将被添加到矩形的底部。                      |
1236| STRUT                     | 5 | 高度按照文本的样式设置。                          |
1237
1238## Affinity
1239
1240位置亲和度枚举。
1241
1242**系统能力:** SystemCapability.Graphics.Drawing
1243
1244| 名称       | 值 | 说明                          |
1245| ---------- | - | ----------------------------- |
1246| UPSTREAM   | 0 | 该位置与文本位置的前一位有关联。 |
1247| DOWNSTREAM | 1 | 该位置与文本位置的后一位有关联。 |
1248
1249## ParagraphBuilder
1250
1251段落生成器。
1252
1253### constructor
1254
1255constructor(paragraphStyle: ParagraphStyle, fontCollection: FontCollection)
1256
1257ParagraphBuilder对象的构造函数。
1258
1259**系统能力**:SystemCapability.Graphics.Drawing
1260
1261**参数:**
1262
1263| 参数名         | 类型                               | 必填 | 说明        |
1264| -------------- | --------------------------------- | ---- | ----------- |
1265| paragraphStyle | [ParagraphStyle](#paragraphstyle) | 是   | 段落样式。   |
1266| fontCollection | [FontCollection](#fontcollection) | 是   | 字体管理器。 |
1267
1268**示例:**
1269
1270```ts
1271import { text } from "@kit.ArkGraphics2D";
1272
1273function textFunc() {
1274  let myTextStyle: text.TextStyle = {
1275    color: { alpha: 255, red: 255, green: 0, blue: 0 },
1276    fontSize: 33,
1277  };
1278  let myParagraphStyle: text.ParagraphStyle = {
1279    textStyle: myTextStyle,
1280    align: text.TextAlign.END,
1281  };
1282  let fontCollection = new text.FontCollection();
1283  let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1284}
1285
1286@Entry
1287@Component
1288struct Index {
1289  fun: Function = textFunc;
1290  build() {
1291    Column() {
1292      Button().onClick(() => {
1293        this.fun();
1294      })
1295    }
1296  }
1297}
1298```
1299
1300### pushStyle
1301
1302 pushStyle(textStyle: TextStyle): void
1303
1304更新文本样式。
1305
1306> **说明:**
1307>
1308> 更新当前文本块的样式 ,直到对应的 [popStyle](#popstyle) 操作被执行,会还原到上一个文本样式。
1309
1310**系统能力**:SystemCapability.Graphics.Drawing
1311
1312**参数:**
1313
1314| 参数名    | 类型       | 必填 | 说明                                                                                                   |
1315| --------- | --------- | ---- | ------------------------------------------------------------------------------------------------------ |
1316| textStyle | [TextStyle](#textstyle) | 是   | 包含了对文本的各种视觉属性的定义,如字体、字号、颜色、字重、字间距、行距、装饰(如下划线、删除线)、文本阴影等。 |
1317
1318**示例:**
1319
1320```ts
1321import { drawing } from '@kit.ArkGraphics2D'
1322import { text } from "@kit.ArkGraphics2D"
1323import { common2D } from "@kit.ArkGraphics2D"
1324import { image } from '@kit.ImageKit';
1325
1326function textFunc() {
1327  let myTextStyle: text.TextStyle = {
1328    color: { alpha: 255, red: 255, green: 0, blue: 0 },
1329    fontSize: 33,
1330  };
1331  let myParagraphStyle: text.ParagraphStyle = {
1332    textStyle: myTextStyle,
1333    align: text.TextAlign.CENTER,
1334  };
1335  let fontCollection = new text.FontCollection();
1336  let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1337  ParagraphGraphBuilder.pushStyle(myTextStyle);
1338}
1339
1340@Entry
1341@Component
1342struct Index {
1343  fun: Function = textFunc;
1344  build() {
1345    Column() {
1346      Button().onClick(() => {
1347        this.fun();
1348      })
1349    }
1350  }
1351}
1352```
1353
1354### popStyle
1355
1356popStyle(): void
1357
1358还原至上一个文本样式。
1359
1360**系统能力**:SystemCapability.Graphics.Drawing
1361
1362**示例:**
1363
1364```ts
1365import { drawing } from '@kit.ArkGraphics2D'
1366import { text } from "@kit.ArkGraphics2D"
1367import { common2D } from "@kit.ArkGraphics2D"
1368import { image } from '@kit.ImageKit';
1369
1370function textFunc() {
1371  let myTextStyle: text.TextStyle = {
1372    color: { alpha: 255, red: 255, green: 0, blue: 0 },
1373    fontSize: 33,
1374  };
1375  let myParagraphStyle: text.ParagraphStyle = {
1376    textStyle: myTextStyle,
1377    align: text.TextAlign.END,
1378  };
1379  let fontCollection = new text.FontCollection();
1380  let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1381  ParagraphGraphBuilder.pushStyle(myTextStyle);
1382  ParagraphGraphBuilder.popStyle();
1383}
1384
1385@Entry
1386@Component
1387struct Index {
1388  fun: Function = textFunc;
1389  build() {
1390    Column() {
1391      Button().onClick(() => {
1392        this.fun();
1393      })
1394    }
1395  }
1396}
1397```
1398
1399### addText
1400
1401addText(text: string): void
1402
1403用于向正在构建的文本段落中插入具体的文本字符串。
1404
1405**系统能力**:SystemCapability.Graphics.Drawing
1406
1407**参数:**
1408
1409| 参数名   | 类型    | 必填 | 说明                       |
1410| ------- | ------- | ---- | -------------------------- |
1411| text    | string  | 是   | 段落中插入的具体文本字符串。 |
1412
1413**示例:**
1414
1415```ts
1416import { drawing } from '@kit.ArkGraphics2D'
1417import { text } from "@kit.ArkGraphics2D"
1418import { common2D } from "@kit.ArkGraphics2D"
1419import { image } from '@kit.ImageKit';
1420
1421function textFunc() {
1422  let myTextStyle: text.TextStyle = {
1423    color: { alpha: 255, red: 255, green: 0, blue: 0 },
1424    fontSize: 33,
1425  };
1426  let myParagraphStyle: text.ParagraphStyle = {
1427    textStyle: myTextStyle,
1428    align: text.TextAlign.END,
1429  };
1430  let fontCollection = new text.FontCollection();
1431  let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1432  ParagraphGraphBuilder.addText("123666");
1433}
1434
1435@Entry
1436@Component
1437struct Index {
1438  fun: Function = textFunc;
1439  build() {
1440    Column() {
1441      Button().onClick(() => {
1442        this.fun();
1443      })
1444    }
1445  }
1446}
1447```
1448
1449### addPlaceholder
1450
1451addPlaceholder(placeholderSpan: PlaceholderSpan): void
1452
1453用于在构建文本段落时插入占位符。
1454
1455**系统能力**:SystemCapability.Graphics.Drawing
1456
1457**参数:**
1458
1459| 参数名          | 类型                                 | 必填 | 说明                                                |
1460| --------------- | ----------------------------------- | ---- | --------------------------------------------------- |
1461| placeholderSpan | [PlaceholderSpan](#placeholderspan) | 是   | 定义了占位符的尺寸、对齐方式、基线类型以及基线偏移量。  |
1462
1463**示例:**
1464
1465```ts
1466import { drawing } from '@kit.ArkGraphics2D'
1467import { text } from "@kit.ArkGraphics2D"
1468import { common2D } from "@kit.ArkGraphics2D"
1469import { image } from '@kit.ImageKit';
1470
1471function textFunc() {
1472  let myParagraphStyle: text.ParagraphStyle = {
1473    align: text.TextAlign.END,
1474  };
1475  let myPlaceholderSpan: text.PlaceholderSpan = {
1476    width: 10000,
1477    height: 10000000,
1478    align: text.PlaceholderAlignment.ABOVE_BASELINE,
1479    baseline: text.TextBaseline.ALPHABETIC,
1480    baselineOffset: 100000
1481  };
1482  let fontCollection = new text.FontCollection();
1483  let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1484  ParagraphGraphBuilder.addPlaceholder(myPlaceholderSpan);
1485}
1486
1487@Entry
1488@Component
1489struct Index {
1490  fun: Function = textFunc;
1491  build() {
1492    Column() {
1493      Button().onClick(() => {
1494        this.fun();
1495      })
1496    }
1497  }
1498}
1499```
1500
1501### build
1502
1503build(): Paragraph
1504
1505用于完成段落的构建过程,生成一个可用于后续排版渲染的段落对象。
1506
1507**系统能力**:SystemCapability.Graphics.Drawing
1508
1509**返回值:**
1510
1511| 类型                     | 说明                           |
1512| ------------------------ | ------------------------------ |
1513| [Paragraph](#paragraph)  | 可用于后续渲染的 Paragraph 对象。|
1514
1515**示例:**
1516
1517```ts
1518import { drawing, text, common2D } from '@kit.ArkGraphics2D'
1519import { image } from '@kit.ImageKit';
1520
1521function textFunc() {
1522  let myTextStyle: text.TextStyle = {
1523    color : {alpha: 255, red: 255, green: 0, blue: 0},
1524    fontSize : 20,
1525  };
1526  let myParagraphStyle: text.ParagraphStyle = {
1527    textStyle : myTextStyle,
1528  };
1529  let fontCollection = new text.FontCollection();
1530  let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1531  ParagraphGraphBuilder.addText("123456789");
1532  let paragraph = ParagraphGraphBuilder.build();
1533  paragraph.layoutSync(200);
1534}
1535
1536@Entry
1537@Component
1538struct Index {
1539  fun: Function = textFunc;
1540  build() {
1541    Column() {
1542      Button().onClick(() => {
1543        this.fun();
1544      })
1545    }
1546  }
1547}
1548```
1549
1550### addSymbol
1551
1552addSymbol(symbolId: number): void
1553
1554用于向正在构建的文本段落中插入具体的符号。
1555
1556**系统能力**:SystemCapability.Graphics.Drawing
1557
1558**参数:**
1559
1560| 参数名    | 类型    | 必填 | 说明                                                        |
1561| -------- | ------- | ---- | ----------------------------------------------------------- |
1562| symbolId | number  | 是   | 要设置的symbol码位,十六进制,当前支持的取值范围为:0xF0000-0xF0C97。可设置的symbol码位及其对应的symbol名称请参阅以下链接中 JSON 文件的 value 字段和 name 字段: [https://gitee.com/openharmony/global_system_resources/blob/master/systemres/main/resources/base/element/symbol.json](https://gitee.com/openharmony/global_system_resources/blob/master/systemres/main/resources/base/element/symbol.json)|
1563
1564**示例:**
1565
1566```ts
1567import { text } from "@kit.ArkGraphics2D";
1568
1569function textFunc() {
1570  let myTextStyle: text.TextStyle = {
1571    color: { alpha: 255, red: 255, green: 0, blue: 0 },
1572    fontSize: 33,
1573  };
1574  let myParagraphStyle: text.ParagraphStyle = {
1575    textStyle: myTextStyle,
1576    align: text.TextAlign.END,
1577  };
1578  let fontCollection = new text.FontCollection();
1579  let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1580  ParagraphGraphBuilder.addSymbol(0xF0000);
1581  let paragraph = ParagraphGraphBuilder.build();
1582}
1583
1584@Entry
1585@Component
1586struct Index {
1587  fun: Function = textFunc;
1588  build() {
1589    Column() {
1590      Button().onClick(() => {
1591        this.fun();
1592      })
1593    }
1594  }
1595}
1596```
1597
1598## TextLine
1599
1600描述段落基础文本行结构的载体。
1601
1602下列API示例中都需先使用[Paragraph](#paragraph)类的[getTextLines()](#gettextlines)接口获取到TextLine对象实例,再通过此实例调用对应方法。
1603### getGlyphCount
1604
1605getGlyphCount(): number
1606
1607获取该文本行中字形的数量。
1608
1609**系统能力**:SystemCapability.Graphics.Drawing
1610
1611**返回值:**
1612
1613| 类型    | 说明               |
1614| ------- | ------------------ |
1615| number  | 该文本行中字形数量,整数。 |
1616
1617**示例:**
1618
1619```ts
1620import { text } from "@kit.ArkGraphics2D"
1621
1622function textFunc() {
1623  let GlyphCount = lines[0].getGlyphCount();
1624}
1625
1626@Entry
1627@Component
1628struct Index {
1629  fun: Function = textFunc;
1630  build() {
1631    Column() {
1632      Button().onClick(() => {
1633        this.fun();
1634      })
1635    }
1636  }
1637}
1638```
1639
1640### getTextRange
1641
1642getTextRange(): Range
1643
1644获取该文本行中的文本在整个段落文本中的索引区间。
1645
1646**系统能力**:SystemCapability.Graphics.Drawing
1647
1648**返回值:**
1649
1650| 类型             | 说明                                              |
1651| ---------------- | ------------------------------------------------ |
1652| [Range](#range)  | 该文本行中的文本在整个段落文本中的索引区间。|
1653
1654**示例:**
1655
1656```ts
1657import { text } from "@kit.ArkGraphics2D"
1658
1659function textFunc() {
1660  let textRange = lines[0].getTextRange();
1661}
1662
1663@Entry
1664@Component
1665struct Index {
1666  fun: Function = textFunc;
1667  build() {
1668    Column() {
1669      Button().onClick(() => {
1670        this.fun();
1671      })
1672    }
1673  }
1674}
1675```
1676
1677### getGlyphRuns
1678
1679getGlyphRuns(): Array\<Run>
1680
1681获取该文本行中的文本渲染单位数组。
1682
1683**系统能力**:SystemCapability.Graphics.Drawing
1684
1685**返回值:**
1686
1687| 类型         | 说明                         |
1688| ------------ | --------------------------- |
1689| Array\<[Run](#run)>  | 该文本行中的文本渲染单位数组。|
1690
1691**示例:**
1692
1693```ts
1694import { text } from "@kit.ArkGraphics2D"
1695
1696function textFunc() {
1697  let runs = lines[0].getGlyphRuns();
1698}
1699
1700@Entry
1701@Component
1702struct Index {
1703  fun: Function = textFunc;
1704  build() {
1705    Column() {
1706      Button().onClick(() => {
1707        this.fun();
1708      })
1709    }
1710  }
1711}
1712```
1713
1714### paint
1715
1716paint(canvas: drawing.Canvas, x: number, y: number): void
1717
1718在画布上以坐标点 (x, y) 为左上角位置绘制该文本行。
1719
1720**系统能力**:SystemCapability.Graphics.Drawing
1721
1722**参数:**
1723
1724| 参数名 | 类型                                                  | 必填 | 说明                    |
1725| ------ | ---------------------------------------------------- | ---- | ---------------------- |
1726| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | 是   | 绘制的目标 canvas。      |
1727|    x   | number                                               | 是   | 绘制的左上角位置的横坐标,浮点数。|
1728|    y   | number                                               | 是   | 绘制的左上角位置的纵坐标,浮点数。|
1729
1730**示例:**
1731
1732```ts
1733import { drawing } from '@kit.ArkGraphics2D'
1734import { text } from "@kit.ArkGraphics2D"
1735import { common2D } from "@kit.ArkGraphics2D"
1736import { image } from '@kit.ImageKit';
1737
1738function textFunc(pixelmap: PixelMap) {
1739  let canvas = new drawing.Canvas(pixelmap);
1740  lines[0].paint(canvas, 0, 0);
1741}
1742
1743@Entry
1744@Component
1745struct Index {
1746  @State pixelmap?: PixelMap = undefined;
1747  fun: Function = textFunc;
1748  build() {
1749    Column() {
1750      Image(this.pixelmap).width(200).height(200);
1751      Button().onClick(() => {
1752        if (this.pixelmap == undefined) {
1753          const color: ArrayBuffer = new ArrayBuffer(160000);
1754          let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } }
1755          this.pixelmap = image.createPixelMapSync(color, opts);
1756        }
1757        this.fun(this.pixelmap);
1758      })
1759    }
1760  }
1761}
1762```
1763
1764## Run
1765
1766文本排版的渲染单元。
1767
1768下列API示例中都需先使用[TextLine](#textline)类的[getGlyphRuns()](#getglyphruns)接口获取到Run对象实例,再通过此实例调用对应方法。
1769
1770### getGlyphCount
1771
1772getGlyphCount(): number
1773
1774获取该渲染单元中字形的数量。
1775
1776**系统能力**:SystemCapability.Graphics.Drawing
1777
1778**返回值:**
1779
1780| 类型     | 说明                |
1781| ------- | -------------------- |
1782| number  | 该渲染单元中字形数量,整数。 |
1783
1784**示例:**
1785
1786```ts
1787import { text } from "@kit.ArkGraphics2D"
1788
1789function textFunc() {
1790  let glyphs = runs[0].getGlyphCount();
1791}
1792
1793@Entry
1794@Component
1795struct Index {
1796  fun: Function = textFunc;
1797  build() {
1798    Column() {
1799      Button().onClick(() => {
1800        this.fun();
1801      })
1802    }
1803  }
1804}
1805```
1806
1807### getGlyphs
1808
1809getGlyphs(): Array\<number>
1810
1811获取该渲染单元中每个字符对应的字形序号。
1812
1813**系统能力**:SystemCapability.Graphics.Drawing
1814
1815**返回值:**
1816
1817| 类型            | 说明                             |
1818| --------------- | -------------------------------- |
1819| Array\<number>  | 该渲染单元中每个字符对应的字形序号。|
1820
1821**示例:**
1822
1823```ts
1824import { text } from "@kit.ArkGraphics2D"
1825
1826function textFunc() {
1827  let glyph = runs[0].getGlyphs();
1828}
1829
1830@Entry
1831@Component
1832struct Index {
1833  fun: Function = textFunc;
1834  build() {
1835    Column() {
1836      Button().onClick(() => {
1837        this.fun();
1838      })
1839    }
1840  }
1841}
1842```
1843
1844### getPositions
1845
1846getPositions(): Array<common2D.Point>
1847
1848获取该渲染单元中每个字形相对于每行的字形位置。
1849
1850**系统能力**:SystemCapability.Graphics.Drawing
1851
1852**返回值:**
1853
1854| 类型                   | 说明                                   |
1855| ---------------------- | ------------------------------------- |
1856| Array<[common2D.Point](js-apis-graphics-common2D.md#point12)>  | 该渲染单元中每个字形相对于每行的字形位置。 |
1857
1858**示例:**
1859
1860```ts
1861import { text } from "@kit.ArkGraphics2D";
1862
1863function textFunc() {
1864  let positions = runs[0].getPositions(); // 获取渲染块全部字形位置
1865}
1866
1867@Entry
1868@Component
1869struct Index {
1870  fun: Function = textFunc;
1871  build() {
1872    Column() {
1873      Button().onClick(() => {
1874        this.fun();
1875      })
1876    }
1877  }
1878}
1879```
1880
1881### getOffsets
1882
1883getOffsets(): Array<common2D.Point>
1884
1885获取该渲染单元中每个字形相对于其索引的偏移量。
1886
1887**系统能力**:SystemCapability.Graphics.Drawing
1888
1889**返回值:**
1890
1891| 类型                   | 说明           |
1892| ---------------------- | -------------- |
1893| Array<[common2D.Point](js-apis-graphics-common2D.md#point12)>  | 该渲染单元中每个字形相对于其索引的偏移量。|
1894
1895**示例:**
1896
1897```ts
1898import { text } from "@kit.ArkGraphics2D";
1899
1900function textFunc() {
1901  let offsets = runs[0].getOffsets();
1902}
1903
1904@Entry
1905@Component
1906struct Index {
1907  fun: Function = textFunc;
1908  build() {
1909    Column() {
1910      Button().onClick(() => {
1911        this.fun();
1912      })
1913    }
1914  }
1915}
1916```
1917
1918### getFont
1919
1920getFont(): drawing.Font
1921
1922获取该渲染单元的字体属性对象实例。
1923
1924**系统能力**:SystemCapability.Graphics.Drawing
1925
1926**返回值:**
1927
1928| 类型                   | 说明           |
1929| ------------------------------------------------- | -------------------------- |
1930| [drawing.Font](js-apis-graphics-drawing.md#font)  | 该渲染单元的字体属性对象实例。|
1931
1932**示例:**
1933
1934```ts
1935import { drawing } from '@kit.ArkGraphics2D'
1936import { text } from "@kit.ArkGraphics2D";
1937
1938function textFunc() {
1939  let font = runs[0].getFont();
1940}
1941
1942@Entry
1943@Component
1944struct Index {
1945  fun: Function = textFunc;
1946  build() {
1947    Column() {
1948      Button().onClick(() => {
1949        this.fun();
1950      })
1951    }
1952  }
1953}
1954```
1955
1956### paint
1957
1958paint(canvas: drawing.Canvas, x: number, y: number): void
1959
1960在画布上以坐标点 (x, y) 为左上角位置绘制该渲染单元。
1961
1962**系统能力**:SystemCapability.Graphics.Drawing
1963
1964**参数:**
1965
1966| 参数名 | 类型                                                  | 必填 | 说明                    |
1967| ------ | ---------------------------------------------------- | ---- | ---------------------- |
1968| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | 是   | 绘制的目标 canvas。      |
1969|    x   | number                                               | 是   | 绘制的左上角位置的横坐标,浮点数。|
1970|    y   | number                                               | 是   | 绘制的左上角位置的纵坐标。浮点数。|
1971
1972**示例:**
1973
1974```ts
1975import { drawing } from '@kit.ArkGraphics2D'
1976import { text } from "@kit.ArkGraphics2D"
1977import { common2D } from "@kit.ArkGraphics2D"
1978import { image } from '@kit.ImageKit';
1979
1980function textFunc() {
1981  const color: ArrayBuffer = new ArrayBuffer(160000);
1982  let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } }
1983  let pixelMap: image.PixelMap = image.createPixelMapSync(color, opts);
1984  let canvas = new drawing.Canvas(pixelMap);
1985  runs[0].paint(canvas, 0, 0);
1986}
1987
1988@Entry
1989@Component
1990struct Index {
1991  fun: Function = textFunc;
1992  build() {
1993    Column() {
1994      Button().onClick(() => {
1995        this.fun();
1996      })
1997    }
1998  }
1999}
2000```
2001
2002## SystemFontType<sup>14+</sup>
2003
2004字体类型枚举,通过位或运算可实现组合类型。
2005
2006**系统能力:** SystemCapability.Graphics.Drawing
2007
2008| 名称 | 值 | 说明 |
2009| - | - | - |
2010| ALL | 1 << 0 | 所有字体类型,包括系统字体类型、风格字体类型和用户已安装字体类型。 |
2011| GENERIC  | 1 << 1 | 系统字体类型。 |
2012| STYLISH  | 1 << 2 | 风格字体类型。风格字体类型是专为2in1设备设计的字体类型。 |
2013| INSTALLED  | 1 << 3 | 用户已安装的字体类型。 |
2014