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