• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.graphics.text (Text)
2
3The Text module provides a set of APIs for text layout and font management. It aims to deliver high-quality typesetting through features like character-to-glyph conversion, kerning, line breaking, alignment, and text measurement. Additionally, it provides font management capabilities, including font registration, font descriptors, and font collection management.
4
5This module provides the following classes for creating complex text paragraphs:
6
7- [TextStyle](#textstyle): defines the font type, size, spacing, and other text properties.
8- [FontCollection](#fontcollection): manages a collection of different fonts.
9- [FontDescriptor](#fontdescriptor14): provides information about font descriptors.
10- [ParagraphStyle](#paragraphstyle): controls line break and word break strategies for the entire paragraph.
11- [ParagraphBuilder](#paragraphbuilder): used to create different paragraph objects.
12- [Paragraph](#paragraph): created by calling [build()](#build) of the **ParagraphBuilder** class.
13- [LineTypeset](#linetypeset18): created by calling [buildLineTypeset()](#buildlinetypeset18) of the **ParagraphBuilder** class.
14- [TextLine](#textline): paragraph text on a line-by-line basis, obtained by calling [getTextLines()](#gettextlines) of the **Paragraph** class.
15- [Run](#run): text typesetting unit, obtained by calling [getGlyphRuns()](#getglyphruns) of the **TextLine** class.
16
17> **NOTE**
18>
19> The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version.
20
21## Modules to Import
22
23```ts
24import { text } from '@kit.ArkGraphics2D';
25```
26
27## text.matchFontDescriptors<sup>18+</sup>
28
29matchFontDescriptors(desc: FontDescriptor): Promise&lt;Array&lt;FontDescriptor&gt;&gt;
30
31Obtains all system font descriptors that match the provided font descriptor. This API uses a promise to return the result.
32
33**System capability**: SystemCapability.Graphics.Drawing
34
35**Parameters**
36
37| Name| Type| Mandatory| Description|
38| - | - | - | - |
39| desc | [FontDescriptor](#fontdescriptor14) | Yes| Font descriptor to match against. If this parameter is left unspecified, all system font descriptors are returned. If a specific value is provided, the matching is performed based on the value provided. If the matching fails, an empty array is returned.|
40
41**Return value**
42
43| Type| Description|
44| - | - |
45| Promise&lt;Array&lt;[FontDescriptor](#fontdescriptor14)&gt;&gt; | Promise used to return all matched system font descriptors.|
46
47**Error codes**
48
49For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
50
51| ID| Error Message|
52| ------- | --------------------------------------------|
53| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. |
54
55**Example**
56
57```ts
58import { text } from "@kit.ArkGraphics2D"
59import { BusinessError } from '@kit.BasicServicesKit';
60
61@Entry
62@Component
63struct Index {
64  build() {
65    Row() {
66      Column() {
67        Button("font descriptor")
68          .fontSize(30)
69          .fontWeight(FontWeight.Bold)
70          .width(300)
71          .height(80)
72          .onClick(() => {
73            console.info(`Get font descriptor start`)
74            let promise = text.matchFontDescriptors({
75              weight: text.FontWeight.W400,
76            })
77            promise.then((data) => {
78              console.info(`Font descriptor array size: ${data.length}`);
79              console.info(`Font descriptor result: ${JSON.stringify(data)}`)
80            }).catch((error: BusinessError) => {
81              console.error(`Failed to match the font descriptor, error: ${JSON.stringify(error)}`);
82            });
83          })
84      }
85      .width('100%')
86    }
87    .height('100%')
88  }
89}
90```
91
92## text.getSystemFontFullNamesByType<sup>14+</sup>
93
94getSystemFontFullNamesByType(fontType: SystemFontType): Promise&lt;Array&lt;string&gt;&gt;
95
96Obtains the full names of all fonts of the specified type. This API uses a promise to return the result.
97
98**System capability**: SystemCapability.Graphics.Drawing
99
100**Parameters**
101
102| Name| Type| Mandatory| Description|
103| - | - | - | - |
104| fontType | [SystemFontType](#systemfonttype14) | Yes| Font type.|
105
106**Return value**
107
108| Type| Description|
109| - | - |
110| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the full names of all fonts of the specified type.|
111
112**Error codes**
113
114For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
115
116| ID| Error Message|
117| ------- | --------------------------------------------|
118| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. |
119
120**Example**
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 font list")
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.getSystemFontFullNamesByType(fontType)
140            promise.then((data) => {
141              console.info(`then font list size: ${data.length}`)
142              data.forEach((fontItem) => {
143                console.info(fontItem)
144              })
145            }).catch((error: BusinessError) => {
146              console.error(`Failed to get font fullNames by type, error: ${JSON.stringify(error)}`);
147            });
148          })
149      }
150      .width('100%')
151    }
152    .height('100%')
153  }
154}
155```
156
157## text.getFontDescriptorByFullName<sup>14+</sup>
158
159getFontDescriptorByFullName(fullName: string, fontType: SystemFontType): Promise&lt;FontDescriptor&gt;
160
161Obtains the font descriptor based on the font name and type. This API uses a promise to return the result.
162
163A font descriptor is a data structure that describes font features. It contains details of the font appearance and properties.
164
165**System capability**: SystemCapability.Graphics.Drawing
166
167**Parameters**
168
169| Name| Type| Mandatory| Description|
170| - | - | - | - |
171| fullName | string | Yes| Font name, corresponding to the value of **fullName** in the **name** table of the corresponding font file. It is obtained by calling [getSystemFontFullNamesByType](#textgetsystemfontfullnamesbytype14).|
172| fontType | [SystemFontType](#systemfonttype14) | Yes| Font type.|
173
174**Return value**
175
176| Type| Description|
177| - | - |
178| Promise&lt;[FontDescriptor](#fontdescriptor14)&gt; | Promise used to return the font descriptor.|
179
180**Error codes**
181
182For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
183
184| ID| Error Message|
185| ------- | --------------------------------------------|
186| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. |
187
188**Example**
189
190```ts
191import { text } from "@kit.ArkGraphics2D"
192import { BusinessError } from '@kit.BasicServicesKit';
193
194@Entry
195@Component
196struct Index {
197  build() {
198    Row() {
199      Column() {
200        Button("get fontDesciptor")
201          .fontSize(30)
202          .fontWeight(FontWeight.Bold)
203          .width(300)
204          .height(80)
205          .onClick(() => {
206            let fontType:text.SystemFontType = text.SystemFontType.GENERIC
207            let promise = text.getFontDescriptorByFullName("HarmonyOS Sans", fontType)
208            promise.then((fontdecriptor) => {
209              console.info(`desc: ${JSON.stringify(fontdecriptor)}`)
210            }).catch((error: BusinessError) => {
211              console.error(`Failed to get fontDescriptor by fullName, error: ${JSON.stringify(error)}`);
212            });
213          })
214      }
215      .width('100%')
216    }
217    .height('100%')
218  }
219}
220```
221
222## TextAlign
223
224Enumerates the text alignment modes.
225
226**System capability**: SystemCapability.Graphics.Drawing
227
228| Name       | Value  | Description                                         |
229| --------- | ---- | ---------------------------------------------- |
230| LEFT      | 0    | Left-aligned.                                 |
231| RIGHT     | 1    | Right-aligned.                                 |
232| CENTER    | 2    | Center-aligned.                                 |
233| JUSTIFY   | 3    | Justified, which means that each line (except the last line) is stretched so that every line has equal width, and the left and right margins are straight.                   |
234| START     | 4    | Aligned with the start position, which depends on [TextDirection](#textdirection).|
235| END       | 5    | Aligned with the end position, which depends on [TextDirection](#textdirection).|
236
237## TextDirection
238
239Enumerates the text directions.
240
241**System capability**: SystemCapability.Graphics.Drawing
242
243| Name    | Value  | Description             |
244| -------- | ---- | ---------------- |
245| RTL      | 0    | Right to left (RTL).|
246| LTR      | 1    | Left to right (LTR).|
247
248## BreakStrategy
249
250Enumerates the text break strategies.
251
252**System capability**: SystemCapability.Graphics.Drawing
253
254| Name         | Value  | Description                                           |
255| ------------- | ---- | ---------------------------------------------- |
256| GREEDY        | 0    | Fills the current line as much as possible without adding hyphens.          |
257| HIGH_QUALITY  | 1    | Optimizes layout and may add hyphens when necessary.               |
258| BALANCED      | 2    | Ensures consistent line width in a paragraph, adding hyphens if needed.|
259
260## WordBreak
261
262Enumerates the word break types.
263
264**System capability**: SystemCapability.Graphics.Drawing
265
266| Name                         | Value  | Description                                                                                                                 |
267|-----------------------------| ---- | -------------------------------------------------------------------------------------------------------------------- |
268| NORMAL                      | 0    | Default mode that break words based on language-specific conventions.                                                                 |
269| BREAK_ALL                   | 1    | Allows breaks within any character in non-CJK text. (CJK means Chinese, Japanese, and Korean.) This value is suitable for Asian text that contains some non-Asian text. For example, it can be used to break consecutive English characters.|
270| BREAK_WORD                  | 2    | Allows breaks between any two characters in non-CJK text. It prioritizes breaking at whitespace or other natural breakpoints to keep words intact. If no breakpoints are found, it breaks between any two characters. For CJK text, this behaves like **NORMAL**.|
271| BREAK_HYPHEN<sup>18+</sup>  | 3    | Attempts to break words at the end of a line using a hyphen. If a hyphen cannot be added, it behaves like **BREAK_WORD**.                       |
272
273## Decoration
274
275Describes a text decoration.
276
277**System capability**: SystemCapability.Graphics.Drawing
278
279| Name                     | Type                                                 | Read Only| Optional| Description                                        |
280| ------------------------- | --------------------------------------------------- | ---- | ---- | -------------------------------------------- |
281| textDecoration            | [TextDecorationType](#textdecorationtype)           | Yes  | Yes  | Type of the decoration. The default value is **NONE**.                      |
282| color                     | [common2D.Color](js-apis-graphics-common2D.md#color)| Yes  | Yes  | Color of the decoration. The default value is transparent.                      |
283| decorationStyle           | [TextDecorationStyle](#textdecorationstyle)         | Yes  | Yes  | Style of the decoration. The default value is **SOLID**.                     |
284| decorationThicknessScale  | number                                              | Yes  | Yes  | Scale factor for the thickness of the decoration line. The value is a floating point number. The default value is **1.0**.|
285
286## TextDecorationType
287
288Enumerates the text decoration types.
289
290**System capability**: SystemCapability.Graphics.Drawing
291
292| Name          | Value| Description       |
293| -------------- | - | ----------- |
294| NONE           | 0 | No decoration is used.|
295| UNDERLINE      | 1 | An underline is used for decoration.     |
296| OVERLINE       | 2 | An overline is used for decoration.    |
297| LINE_THROUGH   | 4 | A strikethrough is used for decoration.     |
298
299## TextDecorationStyle
300
301Enumerates the text decoration styles.
302
303**System capability**: SystemCapability.Graphics.Drawing
304
305| Name  | Value| Description  |
306| ------ | - | ------ |
307| SOLID  | 0 | Solid style. |
308| DOUBLE | 1 | Double style.|
309| DOTTED | 2 | Dotted style.|
310| DASHED | 3 | Dashed style. |
311| WAVY   | 4 | Wavy style.|
312
313## FontWeight
314
315Enumerates the font weights.
316
317**System capability**: SystemCapability.Graphics.Drawing
318
319| Name | Value| Description  |
320| ----- | - | ------- |
321| W100  | 0 | Font weight W100.|
322| W200  | 1 | Font weight W200.|
323| W300  | 2 | Font weight W300.|
324| W400  | 3 | Font weight W400.|
325| W500  | 4 | Font weight W500.|
326| W600  | 5 | Font weight W600.|
327| W700  | 6 | Font weight W700.|
328| W800  | 7 | Font weight W800.|
329| W900  | 8 | Font weight W900.|
330
331## FontWidth
332
333Enumerates the font widths.
334
335**System capability**: SystemCapability.Graphics.Drawing
336
337| Name            | Value| Description      |
338| ---------------- | - | ---------- |
339| ULTRA_CONDENSED  | 1 | Ultra condensed. |
340| EXTRA_CONDENSED  | 2 | Extra condensed. |
341| CONDENSED        | 3 | Condensed. |
342| SEMI_CONDENSED   | 4 | Semi condensed. |
343| NORMAL           | 5 | Normal. |
344| SEMI_EXPANDED    | 6 | Semi expanded. |
345| EXPANDED         | 7 | Expanded. |
346| EXTRA_EXPANDED   | 8 | Extra expanded. |
347| ULTRA_EXPANDED   | 9 | Ultra expanded.|
348
349## FontStyle
350
351Enumerates the font styles.
352
353**System capability**: SystemCapability.Graphics.Drawing
354
355| Name   | Value| Description                                                |
356| ------- | - | ---------------------------------------------------- |
357| NORMAL  | 0 | Normal.                                           |
358| ITALIC  | 1 | Italic. If no italic version is available for the current font, the oblique version will be used instead. |
359| OBLIQUE | 2 | Oblique. If no oblique version is available for the current font, the italic version will be used instead.|
360
361## TextHeightBehavior
362
363Enumerates the text height modifier patterns.
364
365**System capability**: SystemCapability.Graphics.Drawing
366
367| Name                 |  Value| Description                                                 |
368| --------------------- | --- | ---------------------------------------------------- |
369| ALL                   | 0x0 | Allows the first line of the paragraph to rise and the last line to drop.           |
370| DISABLE_FIRST_ASCENT  | 0x1 | Prevents the first line of a paragraph from rising.                  |
371| DISABLE_LAST_ASCENT   | 0x2 | Prevents the last line of a paragraph from dropping.                |
372| DISABLE_ALL           | 0x1 \| 0x2 | Combines the effects of disabling the first line from rising and the last line from dropping.         |
373
374## TextBaseline
375
376Enumerates the text baseline types.
377
378**System capability**: SystemCapability.Graphics.Drawing
379
380| Name       | Value| Description|
381| ----------- | - | ---- |
382| ALPHABETIC  | 0 | Alphabetic baseline, where the letters in Latin alphabets sit on.|
383| IDEOGRAPHIC | 1 | Ideographic baseline, where the baseline is at the bottom of the text area. It is usually used for CJK text.|
384
385## EllipsisMode
386
387Enumerates the ellipsis styles.
388
389**EllipsisMode.START** and **EllipsisMode.MIDDLE** take effect only when text overflows in a single line.
390
391**System capability**: SystemCapability.Graphics.Drawing
392
393| Name  | Value| Description     |
394| ------ | - | --------- |
395| START  | 0 | Places the ellipsis in the text header. It is valid only when **maxLines** is set to **1** in [ParagraphStyle](#paragraphstyle).|
396| MIDDLE | 1 | Places the ellipsis in the middle of the text. It is valid only when **maxLines** is set to **1** in [ParagraphStyle](#paragraphstyle).|
397| END    | 2 | Places the ellipsis at the end of the text.|
398
399## TextShadow
400
401Describes the text shadow.
402
403**System capability**: SystemCapability.Graphics.Drawing
404
405| Name         | Type                                                | Read Only| Optional| Description                              |
406| ------------- | ---------------------------------------------------- | --  | ---  | --------------------------------- |
407| color         | [common2D.Color](js-apis-graphics-common2D.md#color) | Yes |  Yes  | Color of the text shadow. The default value is black (255, 0, 0, 0).       |
408| point         | [common2D.Point](js-apis-graphics-common2D.md#point12) | Yes |  Yes  | Position of the text shadow relative to the text. The horizontal and vertical coordinates must be greater than or equal to 0.   |
409| blurRadius    | number                                               | Yes |  Yes  | Blur radius. The value is a floating point number. The default value is **0.0px**.      |
410
411## RectStyle
412
413Describes the style of a rectangle.
414
415**System capability**: SystemCapability.Graphics.Drawing
416
417| Name              | Type                                                | Read Only| Optional| Description                                     |
418| -----------------  | ---------------------------------------------------- | --  | ---  | ---------------------------------------- |
419| color              | [common2D.Color](js-apis-graphics-common2D.md#color) | Yes |  No  | Color of the rectangle.                |
420| leftTopRadius      | number                                               | Yes |  No  | Left top radius of the rectangle.      |
421| rightTopRadius     | number                                               | Yes |  No  | Right top radius of the rectangle.      |
422| rightBottomRadius  | number                                               | Yes |  No  | Right bottom radius of the rectangle.      |
423| leftBottomRadius   | number                                               | Yes |  No  | Left bottom radius of the rectangle.      |
424
425## FontFeature
426
427Describes a font feature.
428
429**System capability**: SystemCapability.Graphics.Drawing
430
431| Name     | Type                                                | Read Only| Optional| Description                                      |
432| --------- | ---------------------------------------------------- | --  | ---  | ----------------------------------------- |
433| name      | string                                               | Yes |  No  | String identified by the keyword in the font feature key-value pair.      |
434| value     | number                                               | Yes |  No  | Value in the font feature key-value pair.                       |
435
436## FontVariation
437
438Describes a font variation.
439
440**System capability**: SystemCapability.Graphics.Drawing
441
442| Name     | Type                                                | Read Only| Optional| Description                                      |
443| --------- | ---------------------------------------------------- | --  | ---  | ----------------------------------------- |
444| axis      | string                                               | Yes |  No  | String identified by the keyword in the font variation key-value pair.      |
445| value     | number                                               | Yes |  No  | Value in the font variation key-value pair.                       |
446
447## TextStyle
448
449Describes a text style.
450
451**System capability**: SystemCapability.Graphics.Drawing
452
453| Name                     | Type                                    | Read Only| Optional| Description                                                  |
454| ------------- | ---------------------------------------------------- | -- | -- | --------------------------------------------------------- |
455| decoration    | [Decoration](#decoration)                            | Yes| Yes| Text decoration. By default, no decoration is used.            |
456| color         | [common2D.Color](js-apis-graphics-common2D.md#color) | Yes| Yes| Text color. The default color is white.                        |
457| fontWeight    | [FontWeight](#fontweight)                            | Yes| Yes| Font weight. The default value is **W400**. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold (W600), there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect.                        |
458| fontStyle     | [FontStyle](#fontstyle)                              | Yes| Yes| Font style. The default value is **NORMAL**.                         |
459| baseline      | [TextBaseline](#textbaseline)                        | Yes| Yes| Text baseline type. The default value is **ALPHABETIC**.              |
460| fontFamilies  | Array\<string>                                       | Yes| Yes| Array of font families. By default, the array is empty, indicating that all system fonts are matched.                   |
461| fontSize      | number                                               | Yes| Yes| Font size, in units of px. The value is a floating point number. The default value is **14.0**.  |
462| letterSpacing | number                                               | Yes| Yes| Letter spacing, in units of px. The value is a floating point number. The default value is **0.0**. A positive value causes characters to spread farther apart, and a negative value bring characters closer together.|
463| wordSpacing   | number                                               | Yes| Yes| Word spacing, in units of px. The value is a floating point number. The default value is **0.0**.                |
464| heightScale   | number                                               | Yes| Yes| Scale factor of the line height. The value is a floating point number. The default value is **1.0**. This parameter is valid only when **heightOnly** is set to** true**.              |
465| heightOnly    | boolean                                              | Yes| Yes| How the height of the text box is set. The value **true** means that the height of the text box is set based on the font size and the value of **heightScale**, and **false** means that the height is set based on the line height and line spacing. The default value is **false**.|
466| halfLeading   | boolean                                              | Yes| Yes| Whether half leading is enabled. Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite. The default value is **false**.|
467| ellipsis      | string                                               | Yes| Yes| Ellipsis content, which will be used to replace the extra content.      |
468| ellipsisMode  | [EllipsisMode](#ellipsismode)                        | Yes| Yes| Ellipsis type. The default value is **END**, indicating that the ellipsis is at the end of a line.                      |
469| locale        | string                                               | Yes| Yes| Locale. For example, **'en'** indicates English, **'zh-Hans'** indicates Simplified Chinese, and **'zh-Hant'** indicates Traditional Chinese. For details, see ISO 639-1. The default value is an empty string.|
470| baselineShift | number                                               | Yes| Yes| Shift of the baseline. The value is a floating point number. The default value is **0.0px**.                |
471| fontFeatures  | Array\<[FontFeature](#fontfeature)>                  | Yes| Yes| Array of font features.|
472| fontVariations| Array\<[FontVariation](#fontvariation)>              | Yes| Yes| Array of font variations.|
473| textShadows   | Array\<[TextShadow](#textshadow)>                    | Yes| Yes| Array of shadows.|
474| backgroundRect| [RectStyle](#rectstyle)                              | Yes| Yes| Rectangle style.|
475
476## StrutStyle
477
478Describes the strut style, which determines the line spacing, baseline alignment mode, and other properties related to the line height when drawing texts. The strut style is disabled by default.
479
480**System capability**: SystemCapability.Graphics.Drawing
481
482| Name                     | Type                                      | Read Only| Optional| Description                                                                |
483| -------------  | ---------------------------------------------------- | ---- | -- | --------------------------------------------------------------------- |
484| fontFamilies   | Array\<string>                                       | Yes  | Yes| List of font families. By default, the list corresponds to the system's default fonts.                                              |
485| fontStyle      | [FontStyle](#fontstyle)                              | Yes  | Yes| Font style. The default value is **NORMAL**.                                              |
486| fontWidth      | [FontWidth](#fontwidth)                              | Yes  | Yes| Font width. The default value is **NORMAL**.                                               |
487| fontWeight     | [FontWeight](#fontweight)                            | Yes  | Yes| Font weight. The default value is **W400**. The default system font supports font weight adjustment. For other fonts, if the weight is less than W600, there is no variation in stroke thickness. If the weight is greater than or equal to W600, it might result in a fake bold effect.                            |
488| fontSize       | number                                               | Yes  | Yes| Font size, in units of px. The value is a floating point number. The default value is **14.0**.                             |
489| height         | number                                               | Yes  | Yes| Scale factor of the line height. The value is a floating point number. The default value is **1.0**.                                        |
490| leading        | number                                               | Yes  | Yes| Custom leading to be applied to the strut. The value is a floating point number. The default value is **-1.0**.                         |
491| forceHeight    | boolean                                              | Yes  | Yes| Whether to forcibly use the strut height for all lines. The value **true** means to forcibly use the strut height for all lines, and **false** means the opposite. The default value is **false**.    |
492| enabled        | boolean                                              | Yes  | Yes| Whether to enable the strut style. The value **true** means to enable the strut style, and **false** means the opposite. The default value is **false**.             |
493| heightOverride | boolean                                              | Yes  | Yes| Whether to override the height. The value **true** means to override the height, and **false** means the opposite. The default value is **false**.                 |
494| halfLeading    | boolean                                              | Yes  | Yes| Whether half leading is enabled. Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite. The default value is **false**.          |
495
496## FontDescriptor<sup>14+</sup>
497
498Describes the font descriptor information.
499
500**System capability**: SystemCapability.Graphics.Drawing
501
502| Name| Type| Read Only| Optional| Description|
503| - | - | -  | - | - |
504| path | string | No| Yes| Absolute path of the font. Any string is acceptable, but the value must adhere to the system's path constraints. The default value is an empty string.|
505| postScriptName | string | No| Yes| Unique name of the font. Any string is acceptable. The default value is an empty string.|
506| fullName | string | No| Yes| Font name. Any string is acceptable. The default value is an empty string.|
507| fontFamily | string | No| Yes| Family name of the font. Any string is acceptable. The default value is an empty string.|
508| fontSubfamily | string | No| Yes| Subfamily name of the font. Any string is acceptable. The default value is an empty string.|
509| weight | [FontWeight](#fontweight) | No| Yes| Font weight. The default value is **0**.|
510| width | number | No| Yes| Font width. The value is an integer ranging from 1 to 9. The default value is **0**.|
511| italic | number | No| Yes| Whether the font is italic. The value **0** means that the font is not italic, and **1** means the opposite. The default value is **0**.|
512| monoSpace | boolean | No| Yes| Whether the font is monospaced. The value **true** means that the font is monospaced, and **false** means the opposite. The default value is **false**.|
513| symbolic | boolean | No| Yes| Whether the font is symbolic. The value **true** means that the font is symbolic, and **false** means the opposite.|
514
515## FontCollection
516
517Implements a collection of fonts.
518
519### getGlobalInstance
520
521static getGlobalInstance(): FontCollection
522
523Obtains a global **FontCollection** instance.
524
525**System capability**: SystemCapability.Graphics.Drawing
526
527**Return value**
528
529| Type  | Description               |
530| ------ | ------------------ |
531| [FontCollection](#fontcollection) | **FontCollection** instance.|
532
533**Example**
534
535```ts
536import { text } from "@kit.ArkGraphics2D"
537
538function textFunc() {
539  let fontCollection = text.FontCollection.getGlobalInstance();
540}
541
542@Entry
543@Component
544struct Index {
545  fun: Function = textFunc;
546  build() {
547    Column() {
548      Button().onClick(() => {
549        this.fun();
550      })
551    }
552  }
553}
554```
555
556### loadFontSync
557
558loadFontSync(name: string, path: string | Resource): void
559
560Loads a custom font. This API returns the result synchronously. In this API, **name** specifies the alias of the font, and the custom font effect can be displayed only when the value of **name** is set in **fontFamilies** in **[TextStyle](#textstyle)**. The supported font file formats are .ttf and .otf.
561
562**System capability**: SystemCapability.Graphics.Drawing
563
564**Parameters**
565
566| Name| Type              | Mandatory| Description                             |
567| ----- | ------------------ | ---- | --------------------------------------------------------------------------------- |
568| name  | string             | Yes  | Name of the font.                                               |
569| path  | string \| [Resource](../apis-arkui/arkui-ts/ts-types.md#resource) | Yes  | Path of the font file to import. The value must be **file://***absolute path of the font file* or **rawfile/***directory or file name*.|
570
571**Example**
572
573```ts
574import { text } from "@kit.ArkGraphics2D"
575
576let fontCollection: text.FontCollection = new text.FontCollection();
577
578@Entry
579@Component
580struct RenderTest {
581  LoadFontSyncTest() {
582    fontCollection.loadFontSync('Clock_01', 'file:///system/fonts/HarmonyClock_01.ttf')
583    let fontFamilies: Array<string> = ["Clock_01"]
584    let myTextStyle: text.TextStyle = {
585      fontFamilies: fontFamilies
586    };
587    let myParagraphStyle: text.ParagraphStyle = {
588      textStyle: myTextStyle,
589    }
590    let paragraphBuilder: text.ParagraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
591
592    let textData = "Test loadFontSync to load the font HarmonyClock_01.ttf."
593    paragraphBuilder.addText(textData);
594    let paragraph: text.Paragraph = paragraphBuilder.build();
595    paragraph.layoutSync(600);
596  }
597
598  aboutToAppear() {
599    this.LoadFontSyncTest();
600  }
601
602  build() {
603  }
604}
605```
606
607### loadFont<sup>18+</sup>
608
609loadFont(name: string, path: string | Resource): Promise\<void>
610
611Loads a custom font. This API uses a promise to return the result. In this API, **name** specifies the alias of the font, and the custom font effect can be displayed only when the value of **name** is set in **fontFamilies** in **[TextStyle](#textstyle)**. The supported font file formats are ttf and otf.
612
613**System capability**: SystemCapability.Graphics.Drawing
614
615**Parameters**
616
617|   Name| Type              | Mandatory| Description                             |
618|   -----  | ------------------ | ---- | --------------------------------------------------------------------------------- |
619|   name   | string             | Yes  | Name of the font. Any string is acceptable.|
620|   path   | string \| [Resource](../apis-arkui/arkui-ts/ts-types.md#resource) | Yes  | Path of the font file to load. The value must be **file://***absolute path of the font file* or **rawfile/***directory or file name*.|
621
622**Return value**
623
624| Type          | Description                         |
625| -------------- | ----------------------------- |
626| Promise\<void> | Promise that returns no value.|
627
628**Error codes**
629
630For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
631
632| ID| Error Message|
633| ------- | --------------------------------------------|
634| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed.|
635
636**Example**
637
638```ts
639import { text } from "@kit.ArkGraphics2D"
640
641let fontCollection: text.FontCollection = new text.FontCollection();
642
643@Entry
644@Component
645struct RenderTest {
646  async loadFontPromise() {
647    fontCollection.loadFont('testName', 'file:///system/fonts/a.ttf').then((data) => {
648      console.info(`Succeeded in doing loadFont ${JSON.stringify(data)} `);
649    }).catch((error: Error) => {
650      console.error(`Failed to do loadFont, error: ${JSON.stringify(error)} message: ${error.message}`);
651    });
652  }
653
654  aboutToAppear() {
655    this.loadFontPromise();
656  }
657
658  build() {
659  }
660}
661```
662
663### clearCaches
664
665clearCaches(): void
666
667Clears the font cache.
668
669The font cache has a memory limit and a clearing mechanism. It occupies limited memory. You are not advised to clear it unless otherwise required.
670
671**System capability**: SystemCapability.Graphics.Drawing
672
673**Example**
674
675```ts
676import { text } from "@kit.ArkGraphics2D"
677
678@Entry
679@Component
680struct Index {
681  build() {
682    Column() {
683      Button().onClick(() => {
684        text.FontCollection.getGlobalInstance().clearCaches();
685      })
686    }
687  }
688}
689```
690
691## ParagraphStyle
692
693Describes a paragraph style.
694
695**System capability**: SystemCapability.Graphics.Drawing
696
697| Name                | Type                                       | Read Only| Optional| Description                                         |
698| -------------------- | ------------------------------------------ | ---- | ---- | -------------------------------------------- |
699| textStyle            | [TextStyle](#textstyle)                    | Yes  | Yes  | Text style applied to the paragraph. The default value is the initial text style.|
700| textDirection        | [TextDirection](#textdirection)            | Yes  | Yes  | Text direction. The default value is **LTR**.                         |
701| align                | [TextAlign](#textalign)                    | Yes  | Yes  | Text alignment mode. The default value is **START**. This parameter is invalid when the **tab** parameter is configured.|
702| wordBreak            | [WordBreak](#wordbreak)                    | Yes  | Yes  | Word break type. The default value is **BREAK_WORD**.                   |
703| maxLines             | number                                     | Yes  | Yes  | Maximum number of lines. The value is an integer. The default value is **1e9**.                 |
704| breakStrategy        | [BreakStrategy](#breakstrategy)            | Yes  | Yes  | Text break strategy. The default value is **GREEDY**.                       |
705| strutStyle           | [StrutStyle](#strutstyle)                  | Yes  | Yes  | Strut style. The default value is the initial **StrutStyle** object.              |
706| textHeightBehavior   | [TextHeightBehavior](#textheightbehavior)  | Yes  | Yes  | Text height modifier pattern. The default value is **ALL**.                             |
707| tab<sup>18+</sup>   | [TextTab](#texttab18)  | Yes  | Yes  | Alignment mode and position of the text after the tab character in a paragraph. By default, the tab character is replaced with a space. This parameter is invalid when it is used together with the **align** parameter or the **ellipsis** parameter in [TextStyle](#textstyle).|
708
709
710## PlaceholderAlignment
711
712Enumerates the vertical alignment modes of a placeholder relative to the surrounding text.
713
714**System capability**: SystemCapability.Graphics.Drawing
715
716| Name               | Value| Description                  |
717| ------------------- | - | ---------------------- |
718| OFFSET_AT_BASELINE  | 0 | Aligns the baseline of the placeholder to the baseline of the text.    |
719| ABOVE_BASELINE      | 1 | Aligns the bottom edge of the placeholder to the baseline of the text.  |
720| BELOW_BASELINE      | 2 | Aligns the top edge of the placeholder to the baseline of the text.  |
721| TOP_OF_ROW_BOX      | 3 | Aligns the top edge of the placeholder to the top edge of the text.  |
722| BOTTOM_OF_ROW_BOX   | 4 | Aligns the bottom edge of the placeholder to the bottom edge of the text.  |
723| CENTER_OF_ROW_BOX   | 5 | Center-aligned.|
724
725![image_PlaceholderAlignment.png](figures/image_PlaceholderAlignment.png)
726
727> **NOTE**
728>
729> The preceding figure shows only the last three alignment modes. The first three alignment modes are similar. The only difference is that the comparison position changes to the text baseline, which is the green line shown below.
730>
731>![image_Baseline.png](figures/image_Baseline.png)
732
733## PlaceholderSpan
734
735Describes the placeholder style.
736
737**System capability**: SystemCapability.Graphics.Drawing
738
739| Name          | Type                                          | Read Only| Optional| Description                        |
740| -------------- | --------------------------------------------- | ---- | --- | --------------------------- |
741| width          | number                                        | Yes  | No  | Width of the placeholder, in units of px. The value is a floating point number.|
742| height         | number                                        | Yes  | No  | Height of the placeholder, in units of px. The value is a floating point number.|
743| align          | [PlaceholderAlignment](#placeholderalignment) | Yes  | No  | Vertical alignment of the placeholder relative to the surrounding text.|
744| baseline       | [TextBaseline](#textbaseline)                 | Yes  | No  | Type of the text baseline.                  |
745| baselineOffset | number                                        | Yes  | No  | Offset to the text baseline, in units of px. The value is a floating point number. |
746
747## Range
748
749Describes a left-closed and right-open interval.
750
751**System capability**: SystemCapability.Graphics.Drawing
752
753| Name  | Type  | Read Only| Optional| Description           |
754| ----- | ------ | ---- | --- | --------------- |
755| start | number | Yes  | No  | Index of the leftmost point of the interval. The value is an integer.|
756| end   | number | Yes  | No  | Index of the rightmost point of the interval. The value is an integer.|
757
758## Paragraph
759
760Implements a carrier that stores the text content and style. You can perform operations such as layout and drawing.
761
762Before calling any of the following APIs, you must use [build()](#build) of the [ParagraphBuilder](#paragraphbuilder) class to create a **Paragraph** object.
763
764### layoutSync
765
766layoutSync(width: number): void
767
768Performs layout and calculates the positions of all glyphs.
769
770**System capability**: SystemCapability.Graphics.Drawing
771
772**Parameters**
773
774| Name| Type  | Mandatory| Description          |
775| ----- | ------ | ---- | -------------- |
776| width | number | Yes  | Maximum width of a single line, in units of px. The value is a floating point number.|
777
778**Example**
779
780```ts
781paragraph.layoutSync(100);
782```
783
784### layout<sup>18+</sup>
785
786layout(width: number): Promise\<void>
787
788Performs layout and calculates the positions of all glyphs. This API uses a promise to return the result.
789
790**System capability**: SystemCapability.Graphics.Drawing
791
792**Parameters**
793
794|   Name  |    Type              | Mandatory| Description                                   |
795|   -----   |   ------------------  | ---- | --------------------------------------- |
796|   width   | number                | Yes  | Maximum width of a single line, in units of px. The value is a floating point number.   |
797
798**Return value**
799
800| Type          | Description                         |
801| -------------- | ----------------------------- |
802| Promise\<void> | Promise that returns no value.|
803
804**Error codes**
805
806For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
807
808| ID| Error Message|
809| ------- | --------------------------------------------|
810| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. |
811
812**Example**
813
814```ts
815import { drawing, text } from '@kit.ArkGraphics2D'
816import { image } from '@kit.ImageKit';
817
818let textStyle: text.TextStyle = {
819  color: {
820    alpha: 255,
821    red: 255,
822    green: 0,
823    blue: 0
824  },
825  fontSize: 30,
826};
827let paragraphStyle: text.ParagraphStyle = {
828  textStyle: textStyle,
829};
830let fontCollection: text.FontCollection = new text.FontCollection();
831let paragraphBuilder = new text.ParagraphBuilder(paragraphStyle, fontCollection);
832// Add a text string.
833paragraphBuilder.addText("test");
834// Create a paragraph object.
835let paragraph = paragraphBuilder.build();
836
837function textFunc(pixelmap: PixelMap) {
838  // Construct a canvas using an image object.
839  let canvas = new drawing.Canvas(pixelmap);
840  // Draw a text string.
841  paragraph.paint(canvas, 100, 10);
842}
843
844@Entry
845@Component
846struct Index {
847  @State pixelmap?: PixelMap = undefined;
848  fun: Function = textFunc;
849
850  async prepareLayoutPromise() {
851    // Calculate the layout of the paragraph object.
852    paragraph.layout(200).then((data) => {
853      console.info(`Succeeded in doing layout,  ${JSON.stringify(data)}`);
854    }).catch((error: Error) => {
855      console.error(`Failed to do layout, error: ${JSON.stringify(error)} message: ${error.message}`);
856    });
857  }
858
859  aboutToAppear() {
860    this.prepareLayoutPromise();
861  }
862
863  build() {
864    Column() {
865      Image(this.pixelmap).width(200).height(200);
866      Button("layout")
867        .width(100)
868        .height(50)
869        .onClick(() => {
870          const color: ArrayBuffer = new ArrayBuffer(160000);
871          let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } }
872          if (this.pixelmap == undefined) {
873            // Construct an image object.
874            this.pixelmap = image.createPixelMapSync(color, opts);
875          }
876          // Draw the text.
877          this.fun(this.pixelmap);
878        })
879    }
880  }
881}
882```
883
884>**NOTE**
885>
886>The following figure shows the running result of the sample code of the **layout** API after the button is tapped.
887>
888>![image_layout.png](figures/image_layout.png)
889
890### paint
891
892paint(canvas: drawing.Canvas, x: number, y: number): void
893
894Paints the text on the canvas with the coordinate point (x, y) as the upper left corner.
895
896**System capability**: SystemCapability.Graphics.Drawing
897
898**Parameters**
899
900| Name| Type                                                 | Mandatory| Description                   |
901| ------ | ---------------------------------------------------- | ---- | ---------------------- |
902| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | Yes  | Target canvas.        |
903|    x   | number                                               | Yes  | X coordinate of the upper left corner. The value is a floating point number.|
904|    y   | number                                               | Yes  | Y coordinate of the upper left corner. The value is a floating point number.|
905
906**Example**
907
908```ts
909const color: ArrayBuffer = new ArrayBuffer(160000);
910let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } }
911let pixelMap: image.PixelMap = image.createPixelMapSync(color, opts);
912let canvas = new drawing.Canvas(pixelMap);
913paragraph.paint(canvas, 0, 0);
914```
915
916### paintOnPath
917
918paintOnPath(canvas: drawing.Canvas, path: drawing.Path, hOffset: number, vOffset: number): void
919
920Draws text along a path on the canvas.
921
922**System capability**: SystemCapability.Graphics.Drawing
923
924**Parameters**
925
926| Name| Type                                                 | Mandatory| Description                   |
927| ------ | ---------------------------------------------------- | ---- | ---------------------- |
928| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | Yes  | Target canvas.        |
929| path | [drawing.Path](js-apis-graphics-drawing.md#path) | Yes  | Path along which the text is drawn.        |
930|    hOffset   | number                                               | Yes  | Horizontal offset along the path direction. A positive number indicates a position that is ahead along the path from its start point, and a negative number indicates a position that is behind from the start point.|
931|    vOffset   | number                                               | Yes  | Vertical offset along the path direction. A positive number indicates a position on the left side of the path, and a negative number indicates a position on the right side of the path.|
932
933**Example**
934
935```ts
936const color: ArrayBuffer = new ArrayBuffer(160000);
937let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } }
938let pixelMap: image.PixelMap = image.createPixelMapSync(color, opts);
939let canvas = new drawing.Canvas(pixelMap);
940let path = new drawing.Path();
941path.arcTo(20, 20, 180, 180, 180, 90);
942paragraph.paintOnPath(canvas, path, 0, 0);
943```
944
945### getMaxWidth
946
947getMaxWidth(): number
948
949Obtains the maximum width of the line in the text.
950
951**System capability**: SystemCapability.Graphics.Drawing
952
953**Return value**
954
955| Type  | Description      |
956| ------ | --------- |
957| number | Maximum line width, in units of px. The value is a floating point number.|
958
959**Example**
960
961```ts
962let maxWidth = paragraph.getMaxWidth();
963```
964
965### getHeight
966
967getHeight(): number
968
969Obtains the total height of the text.
970
971**System capability**: SystemCapability.Graphics.Drawing
972
973**Return value**
974
975| Type  | Description  |
976| ------ | ----- |
977| number | Total height, in units of px. The value is a floating point number.|
978
979**Example**
980
981```ts
982let height = paragraph.getHeight();
983```
984
985### getLongestLine
986
987getLongestLine(): number
988
989Obtains the longest line in the text.
990
991**System capability**: SystemCapability.Graphics.Drawing
992
993**Return value**
994
995| Type  | Description          |
996| ------ | ------------- |
997| number | Longest line, in units of px. The value is a floating point number.|
998
999**Example**
1000
1001```ts
1002let longestLine = paragraph.getLongestLine();
1003```
1004
1005### getLongestLineWithIndent<sup>13+</sup>
1006
1007getLongestLineWithIndent(): number
1008
1009Obtains the width of the longest line, including its indentation, in the text. You are advised to round up the return value. If the text content is empty, **0** is returned.
1010
1011**System capability**: SystemCapability.Graphics.Drawing
1012
1013**Return value**
1014
1015| Type  | Description          |
1016| ------ | ------------- |
1017| number | Width of the longest line, including its indentation. The value is a floating point number, in px.|
1018
1019**Example**
1020
1021```ts
1022let longestLineWithIndent = paragraph.getLongestLineWithIndent();
1023```
1024
1025### getMinIntrinsicWidth
1026
1027getMinIntrinsicWidth(): number
1028
1029Obtains the minimum intrinsic width of the paragraph.
1030
1031**System capability**: SystemCapability.Graphics.Drawing
1032
1033**Return value**
1034
1035| Type  | Description                          |
1036| ------ | ----------------------------- |
1037| number | Minimum intrinsic width, in units of px. The value is a floating point number.|
1038
1039**Example**
1040
1041```ts
1042let minIntrinsicWidth = paragraph.getMinIntrinsicWidth();
1043```
1044
1045### getMaxIntrinsicWidth
1046
1047getMaxIntrinsicWidth(): number
1048
1049Obtains the maximum intrinsic width of the paragraph.
1050
1051**System capability**: SystemCapability.Graphics.Drawing
1052
1053**Return value**
1054
1055| Type  | Description                          |
1056| ------ | ----------------------------- |
1057| number | Maximum intrinsic width, in units of px. The value is a floating point number.|
1058
1059**Example**
1060
1061```ts
1062let maxIntrinsicWidth = paragraph.getMaxIntrinsicWidth();
1063```
1064
1065### getAlphabeticBaseline
1066
1067getAlphabeticBaseline(): number
1068
1069Obtains the alphabetic baseline.
1070
1071**System capability**: SystemCapability.Graphics.Drawing
1072
1073**Return value**
1074
1075| Type  | Description               |
1076| ------ | ------------------ |
1077| number | Alphabetic baseline, in units of px. The value is a floating point number.|
1078
1079**Example**
1080
1081```ts
1082let alphabeticBaseline = paragraph.getAlphabeticBaseline();
1083```
1084
1085### getIdeographicBaseline
1086
1087getIdeographicBaseline(): number
1088
1089Obtains the ideographic baseline.
1090
1091**System capability**: SystemCapability.Graphics.Drawing
1092
1093**Return value**
1094
1095| Type  | Description                 |
1096| ------ | -------------------- |
1097| number | Ideographic baseline, in units of px. The value is a floating point number.|
1098
1099**Example**
1100
1101```ts
1102let ideographicBaseline = paragraph.getIdeographicBaseline();
1103```
1104
1105### getRectsForRange
1106
1107getRectsForRange(range: Range, widthStyle: RectWidthStyle, heightStyle: RectHeightStyle): Array\<TextBox>
1108
1109Obtains the rectangles occupied by the characters in the range of the text under the given rectangle width and height.
1110
1111**System capability**: SystemCapability.Graphics.Drawing
1112
1113**Parameters**
1114
1115| Name     | Type                                | Mandatory| Description                    |
1116| ----------- | ----------------------------------- | ---- | ------------------------ |
1117| range       | [Range](#range)                     | Yes  | Range of the text. |
1118| widthStyle  | [RectWidthStyle](#rectwidthstyle)   | Yes  | Width of the rectangle.|
1119| heightStyle | [RectHeightStyle](#rectheightstyle) | Yes  | Height of the rectangle.|
1120
1121**Return value**
1122
1123| Type                        | Description       |
1124| --------------------------- | ----------- |
1125| Array\<[TextBox](#textbox)> | Array holding the rectangles obtained.|
1126
1127**Example**
1128
1129```ts
1130let range: text.Range = { start: 0, end: 1};
1131let rects = paragraph.getRectsForRange(range, text.RectWidthStyle.TIGHT, text.RectHeightStyle.TIGHT);
1132```
1133
1134### getRectsForPlaceholders
1135
1136getRectsForPlaceholders(): Array\<TextBox>
1137
1138Obtains the rectangles occupied by all placeholders in the text.
1139
1140**System capability**: SystemCapability.Graphics.Drawing
1141
1142**Return value**
1143
1144| Type                        | Description       |
1145| --------------------------- | ----------- |
1146| Array\<[TextBox](#textbox)> | Array holding the rectangles obtained.|
1147
1148**Example**
1149
1150```ts
1151let placeholderRects = paragraph.getRectsForPlaceholders();
1152```
1153
1154### getGlyphPositionAtCoordinate
1155
1156getGlyphPositionAtCoordinate(x: number, y: number): PositionWithAffinity
1157
1158Obtains the position of a glyph closest to the given coordinates.
1159
1160**System capability**: SystemCapability.Graphics.Drawing
1161
1162**Parameters**
1163
1164| Name| Type  | Mandatory| Description  |
1165| ----- | ------ | ---- | ------ |
1166| x     | number | Yes  | X coordinate. The value is a floating point number.|
1167| y     | number | Yes  | Y coordinate. The value is a floating point number.|
1168
1169**Return value**
1170
1171| Type                                         | Description       |
1172| --------------------------------------------- | ----------- |
1173| [PositionWithAffinity](#positionwithaffinity) | Position of the glyph.|
1174
1175**Example**
1176
1177```ts
1178let positionWithAffinity = paragraph.getGlyphPositionAtCoordinate(0, 0);
1179```
1180
1181### getWordBoundary
1182
1183getWordBoundary(offset: number): Range
1184
1185Obtains the range of the word where the glyph with a given offset is located.
1186
1187**System capability**: SystemCapability.Graphics.Drawing
1188
1189**Parameters**
1190
1191| Name| Type   | Mandatory| Description       |
1192| ------ | ------ | ---- | ----------- |
1193| offset | number | Yes  | Offset of the glyph. The value is an integer.|
1194
1195**Return value**
1196
1197| Type           | Description           |
1198| --------------- | -------------- |
1199| [Range](#range) | Range of the word.|
1200
1201**Example**
1202
1203```ts
1204let wordRange = paragraph.getWordBoundary(0);
1205```
1206
1207### getLineCount
1208
1209getLineCount(): number
1210
1211Obtains the number of text lines.
1212
1213**System capability**: SystemCapability.Graphics.Drawing
1214
1215**Return value**
1216
1217| Type  | Description      |
1218| ------ | --------- |
1219| number | Number of text lines. The value is an integer.|
1220
1221**Example**
1222
1223```ts
1224let lineCount = paragraph.getLineCount();
1225```
1226
1227### getLineHeight
1228
1229getLineHeight(line: number): number
1230
1231Obtains the height of a given line.
1232
1233**System capability**: SystemCapability.Graphics.Drawing
1234
1235**Parameters**
1236
1237| Name| Type  | Mandatory| Description     |
1238| ----- | ------ | ---- | --------- |
1239| line  | number | Yes  | Index of the line. The value is an integer ranging from 0 to getLineCount() – 1.|
1240
1241**Return value**
1242
1243| Type  | Description |
1244| ------ | ---- |
1245| number | Line height.|
1246
1247**Example**
1248
1249```ts
1250let lineHeight = paragraph.getLineHeight(0);
1251```
1252
1253### getLineWidth
1254
1255getLineWidth(line: number): number
1256
1257Obtains the width of a given line.
1258
1259**System capability**: SystemCapability.Graphics.Drawing
1260
1261**Parameters**
1262
1263| Name| Type  | Mandatory| Description     |
1264| ----- | ------ | ---- | --------- |
1265| line  | number | Yes  | Index of the line. The value is an integer ranging from 0 to getLineCount() – 1.|
1266
1267**Return value**
1268
1269| Type  | Description |
1270| ------ | ---- |
1271| number | Line width.|
1272
1273**Example**
1274
1275```ts
1276let lineWidth = paragraph.getLineWidth(0);
1277```
1278
1279### didExceedMaxLines
1280
1281didExceedMaxLines(): boolean
1282
1283Checks whether the number of lines in the paragraph exceeds the maximum.
1284
1285**System capability**: SystemCapability.Graphics.Drawing
1286
1287**Return value**
1288
1289| Type   | Description                                                     |
1290| ------- | -------------------------------------------------------- |
1291| boolean | Check result. The value **true** means that the number of lines exceeds the maximum, and **false** means the opposite.|
1292
1293**Example**
1294
1295```ts
1296let didExceed = paragraph.didExceedMaxLines();
1297```
1298
1299### getTextLines
1300
1301getTextLines(): Array\<TextLine>
1302
1303Obtains all the text lines.
1304
1305**System capability**: SystemCapability.Graphics.Drawing
1306
1307**Return value**
1308
1309| Type                         | Description         |
1310| ----------------------------- | ------------- |
1311| Array\<[TextLine](#textline)> | Array of text lines.|
1312
1313**Example**
1314
1315```ts
1316let lines = paragraph.getTextLines();
1317```
1318
1319### getActualTextRange
1320
1321getActualTextRange(lineNumber: number, includeSpaces: boolean): Range
1322
1323Obtains the actually visible text range in the specified line, excluding any overflow ellipsis.
1324
1325**System capability**: SystemCapability.Graphics.Drawing
1326
1327**Parameters**
1328
1329| Name| Type  | Mandatory| Description     |
1330| ----- | ------ | ---- | --------- |
1331| lineNumber  | number | Yes  | Line number of the text range, starting from 0. This API can only be used to obtain the bounds of existing lines. That is, the line number must start from 0, and the maximum line number is [getLineCount](#getlinecount) - 1.|
1332| includeSpaces  | boolean | Yes  | Whether spaces are included. The value **true** means that spaces are contained, and **false** means the opposite.|
1333
1334**Return value**
1335
1336| Type            | Description                                             |
1337| ---------------- | ------------------------------------------------ |
1338| [Range](#range)  | Text range obtained. If the line index is invalid, **start** and **end** are both 0.|
1339
1340**Example**
1341
1342```ts
1343let rang = paragraph.getActualTextRange(0, true);
1344```
1345
1346
1347### getLineMetrics
1348
1349getLineMetrics(): Array\<LineMetrics>
1350
1351Obtains an array of line measurement information.
1352
1353**System capability**: SystemCapability.Graphics.Drawing
1354
1355**Return value**
1356
1357| Type                         | Description         |
1358| ----------------------------- | ------------- |
1359| Array\<[LineMetrics](#linemetrics)> | Array of line measurement information.|
1360
1361**Example**
1362
1363```ts
1364let arrLineMetrc =  paragraph.getLineMetrics();
1365```
1366
1367### getLineMetrics
1368
1369getLineMetrics(lineNumber: number): LineMetrics | undefined
1370
1371Obtains the line measurement information of a line.
1372
1373**System capability**: SystemCapability.Graphics.Drawing
1374
1375**Parameters**
1376
1377| Name| Type  | Mandatory| Description     |
1378| ----- | ------ | ---- | --------- |
1379| lineNumber  | number | Yes  | Line number, starting from 0.|
1380
1381**Return value**
1382
1383| Type            | Description                                             |
1384| ---------------- | ------------------------------------------------ |
1385| [LineMetrics](#linemetrics) | **LineMetrics** object containing the measurement information if the specified line number is valid and the measurement information exists. If the line number is invalid or the measurement information cannot be obtained, **undefined** is returned.                 |
1386
1387**Example**
1388
1389```ts
1390let lineMetrics =  paragraph.getLineMetrics(0);
1391```
1392
1393## LineTypeset<sup>18+</sup>
1394
1395Implements a carrier that stores the text content and style. It can be used to compute layout details for individual lines of text.
1396
1397Before calling any of the following APIs, you must use [buildLineTypeset()](#buildlinetypeset18) in the [ParagraphBuilder](#paragraphbuilder) class to create a **LineTypeset** object.
1398
1399### getLineBreak<sup>18+</sup>
1400
1401getLineBreak(startIndex: number, width: number): number
1402
1403Obtains the number of characters that can fit in the layout from the specified position within a limited width.
1404
1405**System capability**: SystemCapability.Graphics.Drawing
1406
1407**Parameters**
1408
1409| Name| Type  | Mandatory| Description          |
1410| ----- | ------ | ---- | -------------- |
1411| startIndex | number | Yes| Start position (inclusive) for calculation. The value is an integer in the range [0, total number of text characters). If the parameter is invalid, an exception is thrown.|
1412| width | number | Yes  | Layout width. The value is a floating point number greater than 0, in px.|
1413
1414**Return value**
1415
1416| Type        | Description                        |
1417| ------------ | --------------------------- |
1418| number | Number of characters.|
1419
1420**Error codes**
1421
1422For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1423
1424| ID| Error Message|
1425| ------- | --------------------------------------------|
1426| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3. Parameter verification failed. |
1427
1428**Example**
1429
1430```ts
1431let startIndex = 0;
1432let width = 100.0;
1433let count = lineTypeset.getLineBreak(startIndex, width);
1434```
1435
1436### createLine<sup>18+</sup>
1437
1438createLine(startIndex: number, count: number): TextLine
1439
1440Generates a text line object based on the specified layout range.
1441
1442**System capability**: SystemCapability.Graphics.Drawing
1443
1444**Parameters**
1445
1446| Name| Type  | Mandatory| Description          |
1447| ----- | ------ | ---- | -------------- |
1448| startIndex | number | Yes| Start position for layout calculation. The value is an integer in the range [0, total number of text characters).|
1449| count | number | Yes  | Number of characters from the specified start position. The value is an integer in the range [0, total number of text characters). The sum of **startIndex** and **count** cannot be greater than the total number of text characters. When **count** is **0**, the range is [startIndex, end of the text]. You can use [getLineBreak](#getlinebreak18) to obtain the number of characters that can fit in the layout.|
1450
1451**Return value**
1452
1453| Type        | Description                        |
1454| ------------ | --------------------------- |
1455| [TextLine](#textline) | **TextLine** object generated based on the characters in the text range.|
1456
1457**Error codes**
1458
1459For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1460
1461| ID| Error Message|
1462| ------- | --------------------------------------------|
1463| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3. Parameter verification failed. |
1464
1465**Example**
1466
1467```ts
1468let startIndex = 0;
1469let width = 100.0;
1470let count = lineTypeset.getLineBreak(startIndex, width);
1471let line : text.TextLine = lineTypeset.createLine(startIndex, count);
1472```
1473
1474## RunMetrics
1475
1476Describes the layout information and measurement information of a run of text in a text line.
1477
1478**System capability**: SystemCapability.Graphics.Drawing
1479
1480| Name     | Type                                               | Read Only| Optional| Description       |
1481| --------- | -------------------------------------------------- | ---- | ---- | ----------- |
1482| textStyle | [TextStyle](#textstyle)                             | Yes  | No  | Text style.|
1483| fontMetrics | [drawing.FontMetrics](js-apis-graphics-drawing.md#fontmetrics)| Yes  | No  | Font measurement information.   |
1484
1485## LineMetrics
1486
1487Describes the measurement information of a single line of text in the text layout.
1488
1489**System capability**: SystemCapability.Graphics.Drawing
1490
1491| Name     | Type                                               | Read Only| Optional| Description       |
1492| --------- | -------------------------------------------------- | ---- | ---- | ----------- |
1493| startIndex | number                                            | Yes  | No  | Start index of the line in the text buffer.|
1494| endIndex   | number                                            | Yes  | No  | End index of the line in the text buffer.|
1495| ascent     | number                                            | Yes  | No  | Ascent, that is, the distance from the baseline to the top of the character.|
1496| descent    | number                                            | Yes  | No  | Descent, that is, the distance from the baseline to the bottom of the character.|
1497| height     | number                                            | Yes  | No  | Height of the line, which is Math.round(ascent + descent).|
1498| width      | number                                            | Yes  | No  | Width of the line.                     |
1499| left       | number                        | Yes  | No  | Left edge of the line. The right edge is the value of **left** plus the value of **width**.|
1500| baseline   | number                        | Yes  | No  | Y coordinate of the baseline in the line relative to the top of the paragraph.|
1501| lineNumber   | number                        | Yes  | No  | Line number, starting from 0.|
1502| topHeight   | number                        | Yes  | No  | Height from the top to the current line.|
1503| runMetrics   | Map<number, [RunMetrics](#runmetrics)>                        | Yes  | No  | Mapping between the text index range and the associated font measurement information.|
1504
1505## TextBox
1506
1507Describes the rectangle that holds the text.
1508
1509**System capability**: SystemCapability.Graphics.Drawing
1510
1511| Name     | Type                                               | Read Only| Optional| Description       |
1512| --------- | -------------------------------------------------- | ---- | ---- | ----------- |
1513| rect      | [common2D.Rect](js-apis-graphics-common2D.md#rect) | Yes  | No  | Information about the rectangle.|
1514| direction | [TextDirection](#textdirection)                    | Yes  | No  | Text direction.   |
1515
1516## PositionWithAffinity
1517
1518Describes the position and affinity of a glyph.
1519
1520**System capability**: SystemCapability.Graphics.Drawing
1521
1522| Name     | Type                  | Read Only| Optional| Description                     |
1523| --------- | --------------------- | ---- | ---- | ------------------------ |
1524| position  | number                | Yes  | No  | Index of the glyph relative to the paragraph. The value is an integer. |
1525| affinity  | [Affinity](#affinity) | Yes  | No  | Affinity of the position.              |
1526
1527## RectWidthStyle
1528
1529Enumerates the rectangle width styles.
1530
1531**System capability**: SystemCapability.Graphics.Drawing
1532
1533| Name | Value| Description                                  |
1534| ----- | - | -------------------------------------- |
1535| TIGHT | 0 | If **letterSpacing** is not set, the rectangle conforms tightly to the text it contains. However, if **letterSpacing** is set, a gap is introduced between the rectangle and text.|
1536| MAX   | 1 | The rectangle's width is extended to align with the widest rectangle across all lines.  |
1537
1538## RectHeightStyle
1539
1540Enumerates the rectangle height styles.
1541
1542**System capability**: SystemCapability.Graphics.Drawing
1543
1544| Name                     | Value| Description                                          |
1545| ------------------------- | - | ---------------------------------------------- |
1546| TIGHT                     | 0 | Tight style.                                   |
1547| MAX                       | 1 | Extends the height to match the highest rectangle in all lines.          |
1548| INCLUDE_LINE_SPACE_MIDDLE | 2 | Includes half of the line spacing to both the top and bottom of the rectangle.|
1549| INCLUDE_LINE_SPACE_TOP    | 3 | Includes the line spacing to the top of the rectangle.                     |
1550| INCLUDE_LINE_SPACE_BOTTOM | 4 | Includes the line spacing to the bottom of the rectangle.                     |
1551| STRUT                     | 5 | Sets the height according to the strut style.                         |
1552
1553## Affinity
1554
1555Enumerates the affinity modes.
1556
1557**System capability**: SystemCapability.Graphics.Drawing
1558
1559| Name      | Value| Description                         |
1560| ---------- | - | ----------------------------- |
1561| UPSTREAM   | 0 | The position has affinity for the upstream side of the text position.|
1562| DOWNSTREAM | 1 | The position has affinity for the downstream side of the text position.|
1563
1564## ParagraphBuilder
1565
1566Implements a paragraph builder.
1567
1568### constructor
1569
1570constructor(paragraphStyle: ParagraphStyle, fontCollection: FontCollection)
1571
1572A constructor used to create a **ParagraphBuilder** object.
1573
1574**System capability**: SystemCapability.Graphics.Drawing
1575
1576**Parameters**
1577
1578| Name        | Type                              | Mandatory| Description       |
1579| -------------- | --------------------------------- | ---- | ----------- |
1580| paragraphStyle | [ParagraphStyle](#paragraphstyle) | Yes  | Paragraph style.  |
1581| fontCollection | [FontCollection](#fontcollection) | Yes  | Font collection.|
1582
1583**Example**
1584
1585```ts
1586import { text } from "@kit.ArkGraphics2D";
1587
1588function textFunc() {
1589  let myTextStyle: text.TextStyle = {
1590    color: { alpha: 255, red: 255, green: 0, blue: 0 },
1591    fontSize: 33,
1592  };
1593  let myParagraphStyle: text.ParagraphStyle = {
1594    textStyle: myTextStyle,
1595    align: text.TextAlign.END,
1596  };
1597  let fontCollection = new text.FontCollection();
1598  let paragraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1599}
1600
1601@Entry
1602@Component
1603struct Index {
1604  fun: Function = textFunc;
1605  build() {
1606    Column() {
1607      Button().onClick(() => {
1608        this.fun();
1609      })
1610    }
1611  }
1612}
1613```
1614
1615### pushStyle
1616
1617 pushStyle(textStyle: TextStyle): void
1618
1619Applies a new style to the current text blob.
1620
1621> **NOTE**
1622>
1623> When you update the style of the current text blob, all text added afterward will use this new style.
1624
1625**System capability**: SystemCapability.Graphics.Drawing
1626
1627**Parameters**
1628
1629| Name   | Type      | Mandatory| Description                                                                                                  |
1630| --------- | --------- | ---- | ------------------------------------------------------------------------------------------------------ |
1631| textStyle | [TextStyle](#textstyle) | Yes  | Text style, which describes various visual attributes of text, such as font, font size, color, font weight, word spacing, line spacing, decoration (such as underline and strikethrough), and text shadow.|
1632
1633**Example**
1634
1635```ts
1636import { drawing } from '@kit.ArkGraphics2D'
1637import { text } from "@kit.ArkGraphics2D"
1638import { common2D } from "@kit.ArkGraphics2D"
1639import { image } from '@kit.ImageKit';
1640
1641function textFunc() {
1642  let myTextStyle: text.TextStyle = {
1643    color: { alpha: 255, red: 255, green: 0, blue: 0 },
1644    fontSize: 33,
1645  };
1646  let myParagraphStyle: text.ParagraphStyle = {
1647    textStyle: myTextStyle,
1648    align: text.TextAlign.CENTER,
1649  };
1650  let fontCollection = new text.FontCollection();
1651  let paragraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1652  paragraphBuilder.pushStyle(myTextStyle);
1653}
1654
1655@Entry
1656@Component
1657struct Index {
1658  fun: Function = textFunc;
1659  build() {
1660    Column() {
1661      Button().onClick(() => {
1662        this.fun();
1663      })
1664    }
1665  }
1666}
1667```
1668
1669### popStyle
1670
1671popStyle(): void
1672
1673Restores the previous text style.
1674
1675**System capability**: SystemCapability.Graphics.Drawing
1676
1677**Example**
1678
1679```ts
1680import { drawing } from '@kit.ArkGraphics2D'
1681import { text } from "@kit.ArkGraphics2D"
1682import { common2D } from "@kit.ArkGraphics2D"
1683import { image } from '@kit.ImageKit';
1684
1685function textFunc() {
1686  let myTextStyle: text.TextStyle = {
1687    color: { alpha: 255, red: 255, green: 0, blue: 0 },
1688    fontSize: 33,
1689  };
1690  let myParagraphStyle: text.ParagraphStyle = {
1691    textStyle: myTextStyle,
1692    align: text.TextAlign.END,
1693  };
1694  let fontCollection = new text.FontCollection();
1695  let paragraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1696  paragraphBuilder.pushStyle(myTextStyle);
1697  paragraphBuilder.popStyle();
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### addText
1715
1716addText(text: string): void
1717
1718Inserts a text string into the paragraph being built.
1719
1720**System capability**: SystemCapability.Graphics.Drawing
1721
1722**Parameters**
1723
1724| Name  | Type   | Mandatory| Description                      |
1725| ------- | ------- | ---- | -------------------------- |
1726| text    | string  | Yes  | Exact text string inserted into the paragraph. If an invalid Unicode character is provided, it is displayed as �.|
1727
1728**Example**
1729
1730```ts
1731import { drawing } from '@kit.ArkGraphics2D'
1732import { text } from "@kit.ArkGraphics2D"
1733import { common2D } from "@kit.ArkGraphics2D"
1734import { image } from '@kit.ImageKit';
1735
1736function textFunc() {
1737  let myTextStyle: text.TextStyle = {
1738    color: { alpha: 255, red: 255, green: 0, blue: 0 },
1739    fontSize: 33,
1740  };
1741  let myParagraphStyle: text.ParagraphStyle = {
1742    textStyle: myTextStyle,
1743    align: text.TextAlign.END,
1744  };
1745  let fontCollection = new text.FontCollection();
1746  let paragraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1747  paragraphBuilder.addText("123666");
1748}
1749
1750@Entry
1751@Component
1752struct Index {
1753  fun: Function = textFunc;
1754  build() {
1755    Column() {
1756      Button().onClick(() => {
1757        this.fun();
1758      })
1759    }
1760  }
1761}
1762```
1763
1764### addPlaceholder
1765
1766addPlaceholder(placeholderSpan: PlaceholderSpan): void
1767
1768Inserts a placeholder into the paragraph being built.
1769
1770**System capability**: SystemCapability.Graphics.Drawing
1771
1772**Parameters**
1773
1774| Name         | Type                                | Mandatory| Description                                               |
1775| --------------- | ----------------------------------- | ---- | --------------------------------------------------- |
1776| placeholderSpan | [PlaceholderSpan](#placeholderspan) | Yes  | Placeholder span, which describes the size, alignment, baseline type, and baseline offset of the placeholder. |
1777
1778**Example**
1779
1780```ts
1781import { drawing } from '@kit.ArkGraphics2D'
1782import { text } from "@kit.ArkGraphics2D"
1783import { common2D } from "@kit.ArkGraphics2D"
1784import { image } from '@kit.ImageKit';
1785
1786function textFunc() {
1787  let myParagraphStyle: text.ParagraphStyle = {
1788    align: text.TextAlign.END,
1789  };
1790  let myPlaceholderSpan: text.PlaceholderSpan = {
1791    width: 10000,
1792    height: 10000000,
1793    align: text.PlaceholderAlignment.ABOVE_BASELINE,
1794    baseline: text.TextBaseline.ALPHABETIC,
1795    baselineOffset: 100000
1796  };
1797  let fontCollection = new text.FontCollection();
1798  let paragraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1799  paragraphBuilder.addPlaceholder(myPlaceholderSpan);
1800}
1801
1802@Entry
1803@Component
1804struct Index {
1805  fun: Function = textFunc;
1806  build() {
1807    Column() {
1808      Button().onClick(() => {
1809        this.fun();
1810      })
1811    }
1812  }
1813}
1814```
1815
1816### build
1817
1818build(): Paragraph
1819
1820Creates a paragraph object that can be used for subsequent layout and rendering.
1821
1822**System capability**: SystemCapability.Graphics.Drawing
1823
1824**Return value**
1825
1826| Type                    | Description                          |
1827| ------------------------ | ------------------------------ |
1828| [Paragraph](#paragraph)  | **Paragraph** object that can be used for subsequent rendering.|
1829
1830**Example**
1831
1832```ts
1833import { drawing, text, common2D } from '@kit.ArkGraphics2D'
1834import { image } from '@kit.ImageKit';
1835
1836function textFunc() {
1837  let myTextStyle: text.TextStyle = {
1838    color : {alpha: 255, red: 255, green: 0, blue: 0},
1839    fontSize : 20,
1840  };
1841  let myParagraphStyle: text.ParagraphStyle = {
1842    textStyle : myTextStyle,
1843  };
1844  let fontCollection = new text.FontCollection();
1845  let paragraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1846  paragraphBuilder.addText("123456789");
1847  let paragraph = paragraphBuilder.build();
1848  paragraph.layoutSync(200);
1849}
1850
1851@Entry
1852@Component
1853struct Index {
1854  fun: Function = textFunc;
1855  build() {
1856    Column() {
1857      Button().onClick(() => {
1858        this.fun();
1859      })
1860    }
1861  }
1862}
1863```
1864
1865### buildLineTypeset<sup>18+</sup>
1866
1867buildLineTypeset(): LineTypeset
1868
1869Builds a line typesetter.
1870
1871**System capability**: SystemCapability.Graphics.Drawing
1872
1873**Return value**
1874
1875| Type                    | Description                          |
1876| ------------------------ | ------------------------------ |
1877| [LineTypeset](#linetypeset18)  | **LineTypeset** object that can be used for subsequent rendering.|
1878
1879**Example**
1880
1881```ts
1882import { text } from '@kit.ArkGraphics2D'
1883
1884function test() {
1885  let myParagraphStyle: text.ParagraphStyle = {
1886    align: text.TextAlign.JUSTIFY,
1887  };
1888  let fontCollection = new text.FontCollection();
1889  let paragraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1890  paragraphBuilder.addText("123456789");
1891  let lineTypeset = paragraphBuilder.buildLineTypeset();
1892}
1893
1894@Entry
1895@Component
1896struct Index {
1897  fun: Function = test;
1898  build() {
1899    Column() {
1900      Button().onClick(() => {
1901        this.fun();
1902      })
1903    }
1904  }
1905}
1906```
1907
1908### addSymbol
1909
1910addSymbol(symbolId: number): void
1911
1912Inserts a symbol into the paragraph being built.
1913
1914**System capability**: SystemCapability.Graphics.Drawing
1915
1916**Parameters**
1917
1918| Name   | Type   | Mandatory| Description                                                       |
1919| -------- | ------- | ---- | ----------------------------------------------------------- |
1920| symbolId | number  | Yes  | Symbol code to insert. The value is a hexadecimal number in the range 0xF0000-0xF0C97. For details about the configurable symbol codes (unicode values in the list view), see [HarmonyOS Symbol](https://developer.huawei.com/consumer/en/design/harmonyos-symbol/).|
1921
1922**Example**
1923
1924```ts
1925import { text } from "@kit.ArkGraphics2D";
1926
1927function textFunc() {
1928  let myTextStyle: text.TextStyle = {
1929    color: { alpha: 255, red: 255, green: 0, blue: 0 },
1930    fontSize: 33,
1931  };
1932  let myParagraphStyle: text.ParagraphStyle = {
1933    textStyle: myTextStyle,
1934    align: text.TextAlign.END,
1935  };
1936  let fontCollection = new text.FontCollection();
1937  let paragraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection);
1938  paragraphBuilder.addSymbol(0xF0000);
1939  let paragraph = paragraphBuilder.build();
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## TypographicBounds<sup>18+</sup>
1957
1958Describes the typographic boundaries of a text line. These boundaries depend on the typographic font and font size, not on the characters themselves. For example, for the string " a b " (which has a space before "a" and a space after "b"), the typographic boundaries include the spaces at the beginning and end of the line. Similarly, the strings "j" and "E" have identical typographic boundaries, which are independent of the characters themselves.
1959
1960**System capability**: SystemCapability.Graphics.Drawing
1961
1962| Name| Type| Read Only| Optional| Description|
1963| - | - | - | - | - |
1964| ascent | number | Yes| No| Ascent of a text line. The value is a floating point number.|
1965| descent | number | Yes| No| Descent of a text line. The value is a floating point number.|
1966| leading | number | Yes| No| Leading of a text line. The value is a floating point number.|
1967| width | number | Yes| No| Width of the typographic boundaries. The value is a floating point number.|
1968
1969>**NOTE**
1970>
1971> The following figure shows the meanings of ascent, descent, leading, top, baseline, bottom and next line top, where **width** is the width of the text line, including the left and right spaces; **ascent** is the highest point that the text line reaches upward; **descent** is the lowest point that the text line reaches downward; **leading** is the space between lines of text; **top** is the very highest point of the text line; **baseline** is where the characters sit; **bottom** is the lowest point of the text line; **next line top** is the highest point of the next text line.
1972>
1973>![image_Typographic.png](figures/image_Typographic.png)
1974>
1975> The following figure shows the typographic boundaries of the string " a b ".
1976>
1977>![image_TypographicBounds.png](figures/image_TypographicBounds.png)
1978>
1979> The following figure shows the typographic boundaries of the strings "j" and "E".
1980>
1981>![image_TypographicBounds_Character.png](figures/image_TypographicBounds_Character.png)
1982
1983## CaretOffsetsCallback<sup>18+</sup>
1984
1985type CaretOffsetsCallback = (offset: number, index: number, leadingEdge: boolean) => boolean
1986
1987Defines the callback used to receive the offset and index of each character in a text line object as its parameters.
1988
1989**System capability**: SystemCapability.Graphics.Drawing
1990
1991**Parameters**
1992| Name| Type| Mandatory| Description|
1993| - | - | - | - |
1994| offset | number | Yes| Offset of each character in a text line. The value is a floating point number.|
1995| index | number | Yes| Index of each character in a text line. The value is an integer.|
1996| leadingEdge | boolean | Yes| Whether the cursor is located at the front of the character. The value **true** means that the cursor is located at the front of the character, that is, the offset does not contain the character width. The value **false** means that the cursor is located at the rear of the character, that is, the offset contains the character width.|
1997
1998**Return value**
1999
2000| Type| Description|
2001| - | - |
2002| boolean | Whether to stop calling the callback. The value **true** means to stop calling the callback, and **false** means to continue calling the callback.|
2003
2004## TextLine
2005
2006Implements a carrier that describes the basic text line structure of a paragraph.
2007
2008Before calling any of the following APIs, you must use [getTextLines()](#gettextlines) of the [Paragraph](#paragraph) class or [createLine()](#createline18) of the [LineTypeset](#linetypeset18) class to create a **TextLine** object.
2009### getGlyphCount
2010
2011getGlyphCount(): number
2012
2013Obtains the number of glyphs in this text line.
2014
2015**System capability**: SystemCapability.Graphics.Drawing
2016
2017**Return value**
2018
2019| Type   | Description              |
2020| ------- | ------------------ |
2021| number  | Number of glyphs. The value is an integer.|
2022
2023**Example**
2024
2025```ts
2026let glyphCount = lines[0].getGlyphCount();
2027```
2028
2029### getTextRange
2030
2031getTextRange(): Range
2032
2033Obtains the range of the text in this text line in the entire paragraph.
2034
2035**System capability**: SystemCapability.Graphics.Drawing
2036
2037**Return value**
2038
2039| Type            | Description                                             |
2040| ---------------- | ------------------------------------------------ |
2041| [Range](#range)  | Range of the text in this text line in the entire paragraph.|
2042
2043**Example**
2044
2045```ts
2046let textRange = lines[0].getTextRange();
2047```
2048
2049### getGlyphRuns
2050
2051getGlyphRuns(): Array\<Run>
2052
2053Obtains the array of glyph runs in the text line.
2054
2055**System capability**: SystemCapability.Graphics.Drawing
2056
2057**Return value**
2058
2059| Type        | Description                        |
2060| ------------ | --------------------------- |
2061| Array\<[Run](#run)>  | Array of the runs obtained.|
2062
2063**Example**
2064
2065```ts
2066let runs = lines[0].getGlyphRuns();
2067```
2068
2069### paint
2070
2071paint(canvas: drawing.Canvas, x: number, y: number): void
2072
2073Paints this text line on the canvas with the coordinate point (x, y) as the upper left corner.
2074
2075**System capability**: SystemCapability.Graphics.Drawing
2076
2077**Parameters**
2078
2079| Name| Type                                                 | Mandatory| Description                   |
2080| ------ | ---------------------------------------------------- | ---- | ---------------------- |
2081| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | Yes  | Target canvas.     |
2082|    x   | number                                               | Yes  | X coordinate of the upper left corner. The value is a floating point number.|
2083|    y   | number                                               | Yes  | Y coordinate of the upper left corner. The value is a floating point number.|
2084
2085**Example**
2086
2087<!--code_no_check-->
2088```ts
2089import { drawing } from '@kit.ArkGraphics2D'
2090import { text } from "@kit.ArkGraphics2D"
2091import { common2D } from "@kit.ArkGraphics2D"
2092import { image } from '@kit.ImageKit';
2093
2094function textFunc(pixelmap: PixelMap) {
2095  let canvas = new drawing.Canvas(pixelmap);
2096  lines[0].paint(canvas, 0, 0);
2097}
2098
2099@Entry
2100@Component
2101struct Index {
2102  @State pixelmap?: PixelMap = undefined;
2103  fun: Function = textFunc;
2104  build() {
2105    Column() {
2106      Image(this.pixelmap).width(200).height(200);
2107      Button().onClick(() => {
2108        if (this.pixelmap == undefined) {
2109          const color: ArrayBuffer = new ArrayBuffer(160000);
2110          let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } }
2111          this.pixelmap = image.createPixelMapSync(color, opts);
2112        }
2113        this.fun(this.pixelmap);
2114      })
2115    }
2116  }
2117}
2118```
2119
2120### createTruncatedLine<sup>18+</sup>
2121
2122createTruncatedLine(width: number, ellipsisMode: EllipsisMode, ellipsis: string): TextLine
2123
2124Creates a truncated text line object.
2125
2126**System capability**: SystemCapability.Graphics.Drawing
2127
2128**Parameters**
2129
2130| Name| Type| Mandatory| Description                           |
2131| -| - | - |-------------------------------|
2132| width | number | Yes| Width of the line after truncation. The value is a floating point number.                 |
2133| ellipsisMode | [EllipsisMode](#ellipsismode) | Yes| Ellipsis mode. Currently, only **START** and **END** are supported.|
2134| ellipsis | string | Yes| String used to mark a truncation.                    |
2135
2136**Return value**
2137
2138| Type        | Description                        |
2139| ------------ | --------------------------- |
2140| [TextLine](#textline)  | Truncated text line object.|
2141
2142**Example**
2143
2144<!--code_no_check-->
2145```ts
2146import { drawing, text, common2D } from '@kit.ArkGraphics2D'
2147import { image } from '@kit.ImageKit';
2148
2149function textFunc(pixelmap: PixelMap) {
2150  let canvas = new drawing.Canvas(pixelmap);
2151  let truncatedTextLine = lines[0].createTruncatedLine(100, text.EllipsisMode.START, "...");
2152  truncatedTextLine.paint(canvas, 0, 100);
2153}
2154
2155@Entry
2156@Component
2157struct Index {
2158  @State pixelmap?: PixelMap = undefined;
2159  fun: Function = textFunc;
2160  build() {
2161    Column() {
2162      Image(this.pixelmap).width(200).height(200);
2163      Button().onClick(() => {
2164        if (this.pixelmap == undefined) {
2165          const color: ArrayBuffer = new ArrayBuffer(160000);
2166          let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } }
2167          this.pixelmap = image.createPixelMapSync(color, opts);
2168        }
2169        this.fun(this.pixelmap);
2170      })
2171    }
2172  }
2173}
2174```
2175
2176### getTypographicBounds<sup>18+</sup>
2177
2178getTypographicBounds(): TypographicBounds
2179
2180Obtains the typographic boundaries of this text line. These boundaries depend on the typographic font and font size, but not on the characters themselves. For example, for the string " a b " (which has a space before "a" and a space after "b"), the typographic boundaries include the spaces at the beginning and end of the line. Similarly, the strings "j" and "E" have identical typographic boundaries, which are independent of the characters themselves.
2181
2182>**NOTE**
2183>
2184> The following figure shows the typographic boundaries of the string " a b ".
2185>
2186>![image_TypographicBounds.png](figures/image_TypographicBounds.png)
2187>
2188> The following figure shows the typographic boundaries of the strings "j" and "E".
2189>
2190>![image_TypographicBounds_Character.png](figures/image_TypographicBounds_Character.png)
2191
2192**System capability**: SystemCapability.Graphics.Drawing
2193
2194**Return value**
2195
2196| Type| Description |
2197| -| - |
2198| [TypographicBounds](#typographicbounds18) | Typographic boundaries of the text line.|
2199
2200**Example**
2201
2202```ts
2203let bounds = lines[0].getTypographicBounds();
2204console.info('textLine ascent:' + bounds.ascent + ', descent:' + bounds.descent + ', leading:' + bounds.leading + ', width:' + bounds.width);
2205```
2206
2207### getImageBounds<sup>18+</sup>
2208
2209getImageBounds(): common2D.Rect
2210
2211Obtains the image boundaries of this text line. The image boundaries, equivalent to visual boundaries, depend on the font, font size, and characters. For example, for the string " a b " (which has a space before "a" and a space after "b"), only "a b" are visible to users, and therefore the image boundaries do not include these spaces at the beginning and end of the line. For the strings "j" and "E", their image boundaries are different. Specifically, the width of the boundary for "j" is narrower than that for "E", and the height of the boundary for "j" is taller than that for "E".
2212
2213>**NOTE**
2214>
2215> The following figure shows the image boundaries of the string " a b ".
2216>
2217>![image_ImageBounds.png](figures/image_ImageBounds.png)
2218>
2219> The following figure shows the image boundaries of the strings "j" and "E".
2220>
2221>![image_ImageBounds_Character.png](figures/image_ImageBounds_Character.png)
2222
2223
2224**System capability**: SystemCapability.Graphics.Drawing
2225
2226**Return value**
2227
2228| Type        | Description                        |
2229| ------------ | --------------------------- |
2230| [common2D.Rect](js-apis-graphics-common2D.md#rect)  | Image boundary of the text line.|
2231
2232**Example**
2233
2234```ts
2235let imageBounds = lines[0].getImageBounds();
2236```
2237
2238### getTrailingSpaceWidth<sup>18+</sup>
2239
2240getTrailingSpaceWidth(): number
2241
2242Obtains the width of the spaces at the end of this text line.
2243
2244**System capability**: SystemCapability.Graphics.Drawing
2245
2246**Return value**
2247
2248| Type        | Description                        |
2249| ------------ | --------------------------- |
2250| number | Number of spaces at the end of the text line. The value is a floating point number.|
2251
2252**Example**
2253
2254```ts
2255let trailingSpaceWidth = lines[0].getTrailingSpaceWidth();
2256```
2257
2258### getStringIndexForPosition<sup>18+</sup>
2259
2260getStringIndexForPosition(point: common2D.Point): number
2261
2262Obtains the index of a character at the specified position in the original string.
2263
2264**System capability**: SystemCapability.Graphics.Drawing
2265
2266**Parameters**
2267
2268| Name| Type| Mandatory| Description|
2269| -| - | - | - |
2270| point | [common2D.Point](js-apis-graphics-common2D.md#point12) | Yes| Position of the character.|
2271
2272**Return value**
2273
2274| Type        | Description                        |
2275| ------------ | --------------------------- |
2276| number | Index of the character in the text line. The value is an integer.|
2277
2278**Example**
2279
2280```ts
2281let point : common2D.Point = { x: 15.0, y: 2.0 };
2282let index = lines[0].getStringIndexForPosition(point);
2283```
2284
2285### getOffsetForStringIndex<sup>18+</sup>
2286
2287getOffsetForStringIndex(index: number): number
2288
2289Obtains the offset of a character with the specified index in this text line.
2290
2291**System capability**: SystemCapability.Graphics.Drawing
2292
2293**Parameters**
2294
2295| Name| Type| Mandatory| Description|
2296| -| - | - | - |
2297| index | number | Yes| Index of the character. The value is an integer.|
2298
2299**Return value**
2300
2301| Type        | Description                        |
2302| ------------ | --------------------------- |
2303| number | Offset of the character with the specified index. The value is a floating point number.|
2304
2305**Example**
2306
2307```ts
2308let offset = lines[0].getOffsetForStringIndex(3);
2309```
2310
2311### enumerateCaretOffsets<sup>18+</sup>
2312
2313enumerateCaretOffsets(callback: CaretOffsetsCallback): void
2314
2315Enumerates the offset and index of each character in a text line.
2316
2317**System capability**: SystemCapability.Graphics.Drawing
2318
2319**Parameters**
2320
2321| Name| Type| Mandatory| Description|
2322| -| - | - | - |
2323| callback | [CaretOffsetsCallback](#caretoffsetscallback18) | Yes| Custom function, which contains the offset and index of each character in the text line.|
2324
2325**Example**
2326
2327```ts
2328function callback(offset: number, index: number, leadingEdge: boolean): boolean {
2329  console.info('textLine: offset: ' + offset + ', index: ' + index + ', leadingEdge: ' + leadingEdge);
2330  return index > 50;
2331}
2332lines[0].enumerateCaretOffsets(callback);
2333```
2334
2335### getAlignmentOffset<sup>18+</sup>
2336
2337getAlignmentOffset(alignmentFactor: number, alignmentWidth: number): number
2338
2339Obtains the offset of this text line after alignment based on the alignment factor and alignment width.
2340
2341**System capability**: SystemCapability.Graphics.Drawing
2342
2343**Parameters**
2344
2345| Name| Type| Mandatory| Description|
2346| -| - | - | - |
2347| alignmentFactor | number | Yes| Alignment factor, which determines how text is aligned. The value is a floating point number. A value less than or equal to 0.0 means that the text is left-aligned; a value between 0.0 and 0.5 means that the text is slightly left-aligned; the value 0.5 means that is text is centered; a value between 0.5 and 1 means that the text is slightly right-aligned; a value greater than or equal to 1.0 means that the text is right-aligned.|
2348| alignmentWidth | number | Yes| Alignment width, that is, the width of the text line. The value is a floating point number. If the width is less than the actual width of the text line, **0** is returned.|
2349
2350**Return value**
2351
2352| Type        | Description                        |
2353| ------------ | --------------------------- |
2354| number | Offset required for alignment. The value is a floating point number.|
2355
2356**Example**
2357
2358```ts
2359let alignmentOffset = lines[0].getAlignmentOffset(0.5, 500);
2360```
2361
2362## Run
2363
2364Implements a unit for text layout.
2365
2366Before calling any of the following APIs, you must use [getGlyphRuns()](#getglyphruns) of the [TextLine](#textline) class to create a **Run** object.
2367
2368### getGlyphCount
2369
2370getGlyphCount(): number
2371
2372Obtains the number of glyphs in this run.
2373
2374**System capability**: SystemCapability.Graphics.Drawing
2375
2376**Return value**
2377
2378| Type    | Description               |
2379| ------- | -------------------- |
2380| number  | Number of glyphs. The value is an integer.|
2381
2382**Example**
2383
2384```ts
2385let glyphs = runs[0].getGlyphCount();
2386```
2387
2388### getGlyphs
2389
2390getGlyphs(): Array\<number>
2391
2392Obtains the index of each glyph in this run.
2393
2394**System capability**: SystemCapability.Graphics.Drawing
2395
2396**Return value**
2397
2398| Type           | Description                            |
2399| --------------- | -------------------------------- |
2400| Array\<number>  | Array holding the index of each glyph in the run.|
2401
2402**Example**
2403
2404```ts
2405let glyph = runs[0].getGlyphs();
2406```
2407
2408### getGlyphs<sup>18+</sup>
2409
2410getGlyphs(range: Range): Array\<number>
2411
2412Obtains the index of each glyph in the specified range of this run.
2413
2414**System capability**: SystemCapability.Graphics.Drawing
2415
2416**Parameters**
2417
2418| Name   | Type   | Mandatory| Description                      |
2419| -------- | ------- | ---- | -------------------------- |
2420| range    | [Range](#range)   | Yes  | Range of the glyphs, where **range.start** indicates the start position of the range, and **range.end** indicates the length of the range. If the length is 0, the range is from **range.start** to the end of the run. If **range.end** or **range.start** is set to a negative value, **null**, or **undefined**, **undefined** is returned.|
2421
2422**Return value**
2423
2424| Type           | Description                            |
2425| --------------- | -------------------------------- |
2426| Array\<number>  | Array holding the index of each glyph in the run.|
2427
2428**Example**
2429
2430<!--code_no_check-->
2431```ts
2432import { text } from "@kit.ArkGraphics2D"
2433
2434function textFunc() {
2435  let glyphs = runs[0].getGlyphs(); // Obtain the index of all glyphs of the run.
2436  let glyphsRange = runs[0].getGlyphs ({start:1, end:2}); // Obtain the indices of glyphs in the range starting from position 1, with a length of 2.
2437  glyphsRange = runs[0].getGlyphs({start:-1, end:2}); // -1 is an invalid value, and undefined is returned.
2438  glyphsRange = runs[0].getGlyphs({start:0, end:-10}); // -10 is an invalid value, and undefined is returned.
2439  let glyphsNull = runs[0].getGlyphs(null); // null is an invalid value, and undefined is returned.
2440  let glyphsUndefined = runs[0].getGlyphs(undefined); // undefined is an invalid value, and undefined is returned.
2441}
2442
2443@Entry
2444@Component
2445struct Index {
2446  fun: Function = textFunc;
2447  build() {
2448    Column() {
2449      Button().onClick(() => {
2450        this.fun();
2451      })
2452    }
2453  }
2454}
2455```
2456
2457### getPositions
2458
2459getPositions(): Array<common2D.Point>
2460
2461Obtains the position of each glyph relative to the respective line in this run.
2462
2463**System capability**: SystemCapability.Graphics.Drawing
2464
2465**Return value**
2466
2467| Type                  | Description                                  |
2468| ---------------------- | ------------------------------------- |
2469| Array<[common2D.Point](js-apis-graphics-common2D.md#point12)>  | Array holding the position of each glyph relative to the respective line in the run.|
2470
2471**Example**
2472
2473```ts
2474let positions = runs[0].getPositions();
2475```
2476### getPositions<sup>18+</sup>
2477
2478getPositions(range: Range): Array<common2D.Point>
2479
2480Obtains the position array of each glyph relative to the respective line within the specified range of this run.
2481
2482**System capability**: SystemCapability.Graphics.Drawing
2483
2484**Parameters**
2485
2486| Name   | Type   | Mandatory| Description                      |
2487| -------- | ------- | ---- | -------------------------- |
2488| range    | [Range](#range)   | Yes  | Range of the glyphs, where **range.start** indicates the start position of the range, and **range.end** indicates the length of the range. If the length is 0, the range is from **range.start** to the end of the run. If **range.end** or **range.start** is set to a negative value, **null**, or **undefined**, **undefined** is returned.|
2489
2490**Return value**
2491
2492| Type                  | Description                                  |
2493| ---------------------- | ------------------------------------- |
2494| Array<[common2D.Point](js-apis-graphics-common2D.md#point12)>  | Array holding the position of each glyph relative to the respective line in the run.|
2495
2496**Example**
2497
2498<!--code_no_check-->
2499```ts
2500import { text } from "@kit.ArkGraphics2D";
2501
2502function textFunc() {
2503  let positions = runs[0].getPositions(); // Obtain the positions of all glyphs in the run.
2504  let positionsRange = runs[0].getPositions({start:1, end:2}); // Obtain the positions of glyphs in the range starting from position 1, with a length of 2.
2505  positionsRange = runs[0].getPositions({start:-1, end:2}); // -1 is an invalid value, and undefined is returned.
2506  positionsRange = runs[0].getPositions({start:0, end:-10}); // -10 is an invalid value, and undefined is returned.
2507  let positionsNull = runs[0].getPositions(null); // null is an invalid value, and undefined is returned.
2508  let positionsUndefined = runs[0].getPositions(undefined); // undefined is an invalid value, and undefined is returned.
2509}
2510
2511@Entry
2512@Component
2513struct Index {
2514  fun: Function = textFunc;
2515  build() {
2516    Column() {
2517      Button().onClick(() => {
2518        this.fun();
2519      })
2520    }
2521  }
2522}
2523```
2524
2525### getOffsets
2526
2527getOffsets(): Array<common2D.Point>
2528
2529Obtains the offset of each glyph in this run relative to its index.
2530
2531**System capability**: SystemCapability.Graphics.Drawing
2532
2533**Return value**
2534
2535| Type                  | Description          |
2536| ---------------------- | -------------- |
2537| Array<[common2D.Point](js-apis-graphics-common2D.md#point12)>  | Array holding the offset of each glyph in the run relative to its index.|
2538
2539**Example**
2540
2541```ts
2542let offsets = runs[0].getOffsets();
2543```
2544
2545### getFont
2546
2547getFont(): drawing.Font
2548
2549Obtains the **Font** object of this run.
2550
2551**System capability**: SystemCapability.Graphics.Drawing
2552
2553**Return value**
2554
2555| Type                  | Description          |
2556| ------------------------------------------------- | -------------------------- |
2557| [drawing.Font](js-apis-graphics-drawing.md#font)  | **Font** object of this run.|
2558
2559**Example**
2560
2561```ts
2562let font = runs[0].getFont();
2563```
2564
2565### paint
2566
2567paint(canvas: drawing.Canvas, x: number, y: number): void
2568
2569Paints this run on the canvas with the coordinate point (x, y) as the upper left corner.
2570
2571**System capability**: SystemCapability.Graphics.Drawing
2572
2573**Parameters**
2574
2575| Name| Type                                                 | Mandatory| Description                   |
2576| ------ | ---------------------------------------------------- | ---- | ---------------------- |
2577| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | Yes  | Target canvas.     |
2578|    x   | number                                               | Yes  | X coordinate of the upper left corner. The value is a floating point number.|
2579|    y   | number                                               | Yes  | Y coordinate of the upper left corner. The value is a floating point number.|
2580
2581**Example**
2582
2583<!--code_no_check-->
2584```ts
2585import { drawing } from '@kit.ArkGraphics2D'
2586import { text } from "@kit.ArkGraphics2D"
2587import { common2D } from "@kit.ArkGraphics2D"
2588import { image } from '@kit.ImageKit';
2589
2590function textFunc(pixelmap: PixelMap) {
2591  let canvas = new drawing.Canvas(pixelmap);
2592  runs[0].paint(canvas, 0, 0);
2593}
2594
2595@Entry
2596@Component
2597struct Index {
2598  @State pixelmap?: PixelMap = undefined;
2599  fun: Function = textFunc;
2600  build() {
2601    Column() {
2602      Image(this.pixelmap).width(200).height(200);
2603      Button().onClick(() => {
2604        if (this.pixelmap == undefined) {
2605          const color: ArrayBuffer = new ArrayBuffer(160000);
2606          let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } }
2607          this.pixelmap = image.createPixelMapSync(color, opts);
2608        }
2609        this.fun(this.pixelmap);
2610      })
2611    }
2612  }
2613}
2614```
2615
2616### getStringRange<sup>18+</sup>
2617
2618getStringRange(): Range
2619
2620Obtains the range of glyphs generated by this run.
2621
2622**System capability**: SystemCapability.Graphics.Drawing
2623
2624**Return value**
2625
2626| Type                  | Description          |
2627| ---------------------- | -------------- |
2628| [Range](#range) | Range of the glyphs, where **start** indicates the start position of the range, which is the index relative to the entire paragraph, and **end** indicates the length of the range.|
2629
2630
2631**Example**
2632
2633```ts
2634let runStringRange = runs[0].getStringRange();
2635let location = runStringRange.start;
2636let length = runStringRange.end;
2637```
2638
2639### getStringIndices<sup>18+</sup>
2640
2641getStringIndices(range?: Range): Array\<number>
2642
2643Obtains an array of character indices for glyphs within a specified range of this run, where the indices are offsets relative to the entire paragraph.
2644
2645**System capability**: SystemCapability.Graphics.Drawing
2646
2647**Parameters**
2648
2649| Name   | Type   | Mandatory| Description                      |
2650| -------- | ------- | ---- | -------------------------- |
2651| range    | [Range](#range)   | No  | Range of the glyphs, where **range.start** indicates the start position of the range, and **range.end** indicates the length of the range. If the length is 0, the range is from **range.start** to the end of the run. If **range.end** or **range.start** is set to a negative value, **null**, or **undefined**, **undefined** is returned. If this parameter is not passed, the entire run is obtained.|
2652
2653**Return value**
2654
2655| Type                  | Description          |
2656| ---------------------- | -------------- |
2657| Array\<number>  | Array of character indices.|
2658
2659**Example**
2660
2661<!--code_no_check-->
2662```ts
2663import { text } from "@kit.ArkGraphics2D";
2664
2665function textFunc() {
2666  let indices = runs[0].getStringIndices(); // Obtain the indices of all characters in the run.
2667  let indicesRange = runs[0].getStringIndices({start:1, end:2}); // Obtain the indices of characters in the range starting from position 1, with a length of 2.
2668  indicesRange = runs[0].getStringIndices({start:-1, end:2}); // -1 is an invalid value, and undefined is returned.
2669  indicesRange = runs[0].getStringIndices({start:0, end:-10}); // -10 is an invalid value, and undefined is returned.
2670  let indicesNull = runs[0].getStringIndices(null); // null is an invalid value, and undefined is returned.
2671  let indicesUndefined = runs[0].getStringIndices(undefined); // undefined is an invalid value, and undefined is returned.
2672}
2673
2674@Entry
2675@Component
2676struct Index {
2677  fun: Function = textFunc;
2678  build() {
2679    Column() {
2680      Button().onClick(() => {
2681        this.fun();
2682      })
2683    }
2684  }
2685}
2686```
2687
2688### getImageBounds<sup>18+</sup>
2689
2690getImageBounds(): common2D.Rect
2691
2692Obtains the image boundary of this run. The image boundary, equivalent to a visual boundary, is related to the font, font size, and characters. For example, for the string " a b " (which has a space before "a" and a space after "b"), only "a b" are visible to users, and therefore the image boundary does not include these spaces at the beginning and end.
2693
2694>**NOTE**
2695>
2696>The following figure shows the image boundaries of the string " a b ".
2697>
2698>![image_ImageBounds.png](figures/image_ImageBounds.png)
2699>
2700>The following figure shows the image boundaries of the strings "j" and "E".
2701>
2702>![image_ImageBounds_Character.png](figures/image_ImageBounds_Character.png)
2703
2704**System capability**: SystemCapability.Graphics.Drawing
2705
2706**Return value**
2707
2708| Type                  | Description          |
2709| ---------------------- | -------------- |
2710|   [common2D.Rect](js-apis-graphics-common2D.md#rect)  | Image boundary of the run.|
2711
2712**Example**
2713
2714```ts
2715let bounds = runs[0].getImageBounds();
2716```
2717
2718### getTypographicBounds<sup>18+</sup>
2719
2720getTypographicBounds(): TypographicBounds
2721
2722Obtain the typographic boundaries of this run. These boundaries depend on the typographic font and font size, but not on the characters themselves. For example, for the string " a b " (which has a space before "a" and a space after "b"), the typographic boundaries include the spaces at the beginning and end of the line.
2723
2724>**NOTE**
2725>
2726> The following figure shows the typographic boundaries of the string " a b ".
2727>
2728>![image_TypographicBounds.png](figures/image_TypographicBounds.png)
2729>
2730> The following figure shows the typographic boundaries of the strings "j" and "E".
2731>
2732>![image_TypographicBounds_Character.png](figures/image_TypographicBounds_Character.png)
2733
2734**System capability**: SystemCapability.Graphics.Drawing
2735
2736**Return value**
2737
2738| Type                  | Description          |
2739| ---------------------- | -------------- |
2740|  [TypographicBounds](#typographicbounds18)  | Typographic boundaries of the run.|
2741
2742**Example**
2743
2744```ts
2745let typographicBounds = runs[0].getTypographicBounds();
2746```
2747
2748## TextTab<sup>18+</sup>
2749
2750Implements a paragraph-style text tab, which stores the alignment mode and position.
2751
2752**System capability**: SystemCapability.Graphics.Drawing
2753
2754| Name              | Type                   | Read Only| Optional| Description                                              |
2755| -----------------  | ----------------------- | ---- | ---  | -------------------------------------------------- |
2756| alignment          | [TextAlign](#textalign) | Yes  |  No | Alignment mode of the text following the tab character in a paragraph. It can be set to **LEFT**, **RIGHT**, and **CENTER** defined in [TextAlign](#textalign). Other enumerated values have the effect of left alignment. The default value is left alignment.|
2757| location           | number                  | Yes  |  No | Alignment position of the text following the tab character. The value is a floating point number, in px. The minimum value is 1.0. When the value is less than 1.0, the tab character is replaced with a space.|
2758
2759**Example**
2760
2761**alignment** is **CENTER**, **location** is **200**, and the text is "12/t345".
2762
2763![image_AlignmentCenter.png](figures/image_AlignmentCenter.png)
2764
2765**alignment** is **LEFT**, **location** is **100**, and the text is "abccccccccc/tdef".
2766
2767![image_AlignmentLeft.png](figures/image_AlignmentLeft.png)
2768
2769**alignment** is **RIGHT**, **location** is **100**, and the text is "aabcdef/tg hi/tjkl/tmno/tp qr".
2770
2771![image_AlignmentRight.png](figures/image_AlignmentRight.png)
2772
2773## SystemFontType<sup>14+</sup>
2774
2775Enumerates the font types, which can be combined through bitwise OR operations.
2776
2777**System capability**: SystemCapability.Graphics.Drawing
2778
2779| Name| Value| Description|
2780| - | - | - |
2781| ALL | 1 << 0 | All font types, including the system font type, style font type, and user-installed font type.|
2782| GENERIC  | 1 << 1 | System font type.|
2783| STYLISH  | 1 << 2 | Style font type. The style font type is designed for 2-in-1 devices.|
2784| INSTALLED  | 1 << 3 | Font type that has been installed.|
2785| CUSTOMIZED<sup>18+</sup>  | 1 << 4 | Custom font type.|
2786