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- [ParagraphBuilder](#paragraphbuilder): paragraph builder, which controls the generation of different paragraph objects. 12- [TextLine](#textline): carrier of the paragraph text in lines. It is obtained by calling [getTextLines()](#gettextlines) in the **Paragraph** class. 13- [Run](#run): rendering unit used for text typesetting. It is obtained by calling [getGlyphRuns()](#getglyphruns) in the **TextLine** class. 14 15> **NOTE** 16> 17> 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. 18 19## Modules to Import 20 21```ts 22import { text } from '@kit.ArkGraphics2D'; 23``` 24 25## text.getSystemFontFullNamesByType<sup>14+</sup> 26 27getSystemFontFullNamesByType(fontType: SystemFontType): Promise<Array<string>> 28 29Obtains the names of all fonts of the specified type. This API uses a promise to return the result. 30 31**System capability**: SystemCapability.Graphics.Drawing 32 33**Parameters** 34 35| Name| Type| Mandatory| Description| 36| - | - | - | - | 37| fontType | [SystemFontType](#systemfonttype14) | Yes| Font type.| 38 39**Return value** 40 41| Type| Description| 42| - | - | 43| Promise<Array<string>> | Promise used to return the names of all fonts of the specified type.| 44 45**Error codes** 46 47For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 48 49| ID| Error Message| 50| ------- | --------------------------------------------| 51| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. | 52 53**Example** 54 55```ts 56import { text } from "@kit.ArkGraphics2D" 57import { BusinessError } from '@kit.BasicServicesKit'; 58 59@Entry 60@Component 61struct Index { 62 build() { 63 Row() { 64 Column() { 65 Button("get font list") 66 .fontSize(30) 67 .fontWeight(FontWeight.Bold) 68 .width(300) 69 .height(80) 70 .onClick(() => { 71 let fontType:text.SystemFontType = text.SystemFontType.GENERIC 72 let promise = text.getSystemFontFullNamesByType(fontType) 73 promise.then((data) => { 74 console.info(`then font list size: ${data.length}`) 75 data.forEach((fontItem) => { 76 console.info(fontItem) 77 }) 78 }).catch((error: BusinessError) => { 79 console.error(`Failed to get font fullNames by type, error: ${JSON.stringify(error)}`); 80 }); 81 }) 82 } 83 .width('100%') 84 } 85 .height('100%') 86 } 87} 88``` 89 90## text.getFontDescriptorByFullName<sup>14+</sup> 91 92getFontDescriptorByFullName(fullName: string, fontType: SystemFontType): Promise<FontDescriptor> 93 94Obtains the font descriptor based on the font name and type. This API uses a promise to return the result. 95 96A font descriptor is a data structure that describes font features. It contains details of the font appearance and properties. 97 98**System capability**: SystemCapability.Graphics.Drawing 99 100**Parameters** 101 102| Name| Type| Mandatory| Description| 103| - | - | - | - | 104| 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.| 105| fontType | [SystemFontType](#systemfonttype14) | Yes| Font type.| 106 107**Return value** 108 109| Type| Description| 110| - | - | 111| Promise<[FontDescriptor](#fontdescriptor14)> | Promise used to return the font descriptor.| 112 113**Error codes** 114 115For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 116 117| ID| Error Message| 118| ------- | --------------------------------------------| 119| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | 120 121**Example** 122 123```ts 124import { text } from "@kit.ArkGraphics2D" 125import { BusinessError } from '@kit.BasicServicesKit'; 126 127@Entry 128@Component 129struct Index { 130 build() { 131 Row() { 132 Column() { 133 Button("get fontDesciptor") 134 .fontSize(30) 135 .fontWeight(FontWeight.Bold) 136 .width(300) 137 .height(80) 138 .onClick(() => { 139 let fontType:text.SystemFontType = text.SystemFontType.GENERIC 140 let promise = text.getFontDescriptorByFullName("HarmonyOS Sans", fontType) 141 promise.then((fontdecriptor) => { 142 console.info(`desc: ${JSON.stringify(fontdecriptor)}`) 143 }).catch((error: BusinessError) => { 144 console.error(`Failed to get fontDescriptor by fullName, error: ${JSON.stringify(error)}`); 145 }); 146 }) 147 } 148 .width('100%') 149 } 150 .height('100%') 151 } 152} 153``` 154 155## TextAlign 156 157Enumerates the text alignment modes. 158 159**System capability**: SystemCapability.Graphics.Drawing 160 161| Name | Value | Description | 162| --------- | ---- | ---------------------------------------------- | 163| LEFT | 0 | Left-aligned. | 164| RIGHT | 1 | Right-aligned. | 165| CENTER | 2 | Center-aligned. | 166| 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. | 167| START | 4 | Aligned with the start position, which depends on [TextDirection](#textdirection).| 168| END | 5 | Aligned with the end position, which depends on [TextDirection](#textdirection).| 169 170## TextDirection 171 172Enumerates the text directions. 173 174**System capability**: SystemCapability.Graphics.Drawing 175 176| Name | Value | Description | 177| -------- | ---- | ---------------- | 178| RTL | 0 | Right to left (RTL).| 179| LTR | 1 | Left to right (LTR).| 180 181## BreakStrategy 182 183Enumerates the text break strategies. 184 185**System capability**: SystemCapability.Graphics.Drawing 186 187| Name | Value | Description | 188| ------------- | ---- | ---------------------------------------------- | 189| GREEDY | 0 | Each line is filled as much as possible during line break. No hyphen is automatically added. | 190| HIGH_QUALITY | 1 | Text continuity is preferentially considered during line break. If necessary, hyphens are automatically added. | 191| BALANCED | 2 | Each line of a paragraph has the same width. If necessary, hyphens are automatically added.| 192 193## WordBreak 194 195Enumerates the word break types. 196 197**System capability**: SystemCapability.Graphics.Drawing 198 199| Name | Value | Description | 200| ----------- | ---- | -------------------------------------------------------------------------------------------------------------------- | 201| NORMAL | 0 | Default mode. Word breaks are allowed between words as appropriate to the relevant language writing systems. | 202| 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.| 203| BREAK_WORD | 2 | Works in the same way as **BREAK_ALL**, except that it does not break unbreakable words. | 204 205## Decoration 206 207Describes a text decoration. 208 209**System capability**: SystemCapability.Graphics.Drawing 210 211| Name | Type | Read Only| Optional| Description | 212| ------------------------- | --------------------------------------------------- | ---- | ---- | -------------------------------------------- | 213| textDecoration | [TextDecorationType](#textdecorationtype) | Yes | Yes | Type of the decoration. The default value is **NONE**. | 214| color | [common2D.Color](js-apis-graphics-common2D.md#color)| Yes | Yes | Color of the decoration. The default value is transparent. | 215| decorationStyle | [TextDecorationStyle](#textdecorationstyle) | Yes | Yes | Style of the decoration. The default value is **SOLID**. | 216| 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.| 217 218## TextDecorationType 219 220Enumerates the text decoration types. 221 222**System capability**: SystemCapability.Graphics.Drawing 223 224| Name | Value| Description | 225| -------------- | - | ----------- | 226| NONE | 0 | No decoration is used.| 227| UNDERLINE | 1 | An underline is used for decoration. | 228| OVERLINE | 2 | An overline is used for decoration. | 229| LINE_THROUGH | 3 | A strikethrough is used for decoration. | 230 231## TextDecorationStyle 232 233Enumerates the text decoration styles. 234 235**System capability**: SystemCapability.Graphics.Drawing 236 237| Name | Value| Description | 238| ------ | - | ------ | 239| SOLID | 0 | Solid style. | 240| DOUBLE | 1 | Double style.| 241| DOTTED | 2 | Dotted style.| 242| DASHED | 3 | Dashed style. | 243| WAVY | 4 | Wavy style.| 244 245## FontWeight 246 247Enumerates the font weights. 248 249**System capability**: SystemCapability.Graphics.Drawing 250 251| Name | Value| Description | 252| ----- | - | ------- | 253| W100 | 0 | Font weight W100.| 254| W200 | 1 | Font weight W200.| 255| W300 | 2 | Font weight W300.| 256| W400 | 3 | Font weight W400.| 257| W500 | 4 | Font weight W500.| 258| W600 | 5 | Font weight W600.| 259| W700 | 6 | Font weight W700.| 260| W800 | 7 | Font weight W800.| 261| W900 | 8 | Font weight W900.| 262 263## FontWidth 264 265Enumerates the font widths. 266 267**System capability**: SystemCapability.Graphics.Drawing 268 269| Name | Value| Description | 270| ---------------- | - | ---------- | 271| ULTRA_CONDENSED | 1 | Ultra condensed. | 272| EXTRA_CONDENSED | 2 | Extra condensed. | 273| CONDENSED | 3 | Condensed. | 274| SEMI_CONDENSED | 4 | Semi condensed. | 275| NORMAL | 5 | Normal. | 276| SEMI_EXPANDED | 6 | Semi expanded. | 277| EXPANDED | 7 | Expanded. | 278| EXTRA_EXPANDED | 8 | Extra expanded. | 279| ULTRA_EXPANDED | 9 | Ultra expanded.| 280 281## FontStyle 282 283Enumerates the font styles. 284 285**System capability**: SystemCapability.Graphics.Drawing 286 287| Name | Value| Description | 288| ------- | - | ---------------------------------------------------- | 289| NORMAL | 0 | Normal. | 290| ITALIC | 1 | Italic. If no italic version is available for the current font, the oblique version will be used instead. | 291| OBLIQUE | 2 | Oblique. If no oblique version is available for the current font, the italic version will be used instead.| 292 293## TextHeightBehavior 294 295Enumerates the text height modifier patterns. 296 297**System capability**: SystemCapability.Graphics.Drawing 298 299| Name | Value| Description | 300| --------------------- | --- | ---------------------------------------------------- | 301| ALL | 0x0 | Enables ascent for the first and last rows of a paragraph. | 302| DISABLE_FIRST_ASCENT | 0x1 | Disables ascent for the first row of a paragraph. | 303| DISABLE_LAST_ASCENT | 0x2 | Disables ascent for the last row of a paragraph. | 304| DISABLE_ALL | 0x3 | Disables ascent for the first and last rows of a paragraph. | 305 306## TextBaseline 307 308Enumerates the text baseline types. 309 310**System capability**: SystemCapability.Graphics.Drawing 311 312| Name | Value| Description| 313| ----------- | - | ---- | 314| ALPHABETIC | 0 | Alphabetic baseline, where the letters in Latin alphabets sit on.| 315| IDEOGRAPHIC | 1 | Ideographic baseline, where the baseline is at the bottom of the text area. It is usually used for CJK text.| 316 317## EllipsisMode 318 319Enumerates the ellipsis styles. 320 321**EllipsisMode.START** and **EllipsisMode.MIDDLE** take effect only when text overflows in a single line. 322 323**System capability**: SystemCapability.Graphics.Drawing 324 325| Name | Value| Description | 326| ------ | - | --------- | 327| START | 0 | Places the ellipsis in the text header.| 328| MIDDLE | 1 | Places the ellipsis in the middle of the text.| 329| END | 2 | Places the ellipsis at the end of the text.| 330 331## TextShadow 332 333Describes the text shadow. 334 335**System capability**: SystemCapability.Graphics.Drawing 336 337| Name | Type | Read Only| Optional| Description | 338| ------------- | ---------------------------------------------------- | -- | --- | --------------------------------- | 339| 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). | 340| 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. | 341| blurRadius | number | Yes | Yes | Blur radius. The value is a floating point number. The default value is **0.0px**. | 342 343## RectStyle 344 345Describes the style of a rectangle. 346 347**System capability**: SystemCapability.Graphics.Drawing 348 349| Name | Type | Read Only| Optional| Description | 350| ----------------- | ---------------------------------------------------- | -- | --- | ---------------------------------------- | 351| color | [common2D.Color](js-apis-graphics-common2D.md#color) | Yes | No | Color of the rectangle. | 352| leftTopRadius | number | Yes | No | Left top radius of the rectangle. | 353| rightTopRadius | number | Yes | No | Right top radius of the rectangle. | 354| rightBottomRadius | number | Yes | No | Right bottom radius of the rectangle. | 355| leftBottomRadius | number | Yes | No | Left bottom radius of the rectangle. | 356 357## FontFeature 358 359Describes a font feature. 360 361**System capability**: SystemCapability.Graphics.Drawing 362 363| Name | Type | Read Only| Optional| Description | 364| --------- | ---------------------------------------------------- | -- | --- | ----------------------------------------- | 365| name | string | Yes | No | String identified by the keyword in the font feature key-value pair. | 366| value | number | Yes | No | Value in the font feature key-value pair. | 367 368## FontVariation 369 370Describes a font variation. 371 372**System capability**: SystemCapability.Graphics.Drawing 373 374| Name | Type | Read Only| Optional| Description | 375| --------- | ---------------------------------------------------- | -- | --- | ----------------------------------------- | 376| axis | string | Yes | No | String identified by the keyword in the font variation key-value pair. | 377| value | number | Yes | No | Value in the font variation key-value pair. | 378 379## TextStyle 380 381Describes a text style. 382 383**System capability**: SystemCapability.Graphics.Drawing 384 385| Name | Type | Read Only| Optional| Description | 386| ------------- | ---------------------------------------------------- | -- | -- | --------------------------------------------------------- | 387| decoration | [Decoration](#decoration) | Yes| Yes| Text decoration. The default value is the initial decoration. | 388| color | [common2D.Color](js-apis-graphics-common2D.md#color) | Yes| Yes| Font color. The default color is white. | 389| 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. | 390| fontStyle | [FontStyle](#fontstyle) | Yes| Yes| Font style. The default value is **NORMAL**. | 391| baseline | [TextBaseline](#textbaseline) | Yes| Yes| Text baseline type. The default value is **ALPHABETIC**. | 392| fontFamilies | Array\<string> | Yes| Yes| List of font families. By default, the list corresponds to the system's default fonts. | 393| fontSize | number | Yes| Yes| Font size, in units of px. The value is a floating point number. The default value is **14.0**. | 394| 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.| 395| wordSpacing | number | Yes| Yes| Word spacing, in units of px. The value is a floating point number. The default value is **0.0**. | 396| 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**. | 397| 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**.| 398| 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**.| 399| ellipsis | string | Yes| Yes| Ellipsis content, which will be used to replace the extra content. | 400| ellipsisMode | [EllipsisMode](#ellipsismode) | Yes| Yes| Ellipsis type. The default value is **END**, indicating that the ellipsis is at the end of a line. | 401| 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.| 402| baselineShift | number | Yes| Yes| Shift of the baseline. The value is a floating point number. The default value is **0.0px**. | 403| fontFeatures | Array\<[FontFeature](#fontfeature)> | Yes| Yes| Array of font features.| 404| fontVariations| Array\<[FontVariation](#fontvariation)> | Yes| Yes| Array of font variations.| 405| textShadows | Array\<[TextShadow](#textshadow)> | Yes| Yes| Array of text shadows.| 406| backgroundRect| [RectStyle](#rectstyle) | Yes| Yes| Rectangle style.| 407 408## StrutStyle 409 410Describes 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. 411 412**System capability**: SystemCapability.Graphics.Drawing 413 414| Name | Type | Read Only| Optional| Description | 415| ------------- | ---------------------------------------------------- | ---- | -- | --------------------------------------------------------------------- | 416| fontFamilies | Array\<string> | Yes | Yes| Font families. The default value is the system fonts. | 417| fontStyle | [FontStyle](#fontstyle) | Yes | Yes| Font style. The default value is **NORMAL**. | 418| fontWidth | [FontWidth](#fontwidth) | Yes | Yes| Font width. The default value is **NORMAL**. | 419| 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. | 420| fontSize | number | Yes | Yes| Font size, in units of px. The value is a floating point number. The default value is **14.0**. | 421| height | number | Yes | Yes| Scale factor of the line height. The value is a floating point number. The default value is **1.0**. | 422| 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**. | 423| 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**. | 424| 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**. | 425| 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**. | 426| 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**. | 427 428## FontDescriptor<sup>14+</sup> 429 430Describes the font descriptor information. 431 432**System capability**: SystemCapability.Graphics.Drawing 433 434| Name| Type| Read Only| Optional| Description| 435| - | - | - | - | - | 436| path | string | No| Yes| Absolute path of the font. Any value is acceptable. The default value is an empty string.| 437| postScriptName | string | No| Yes| Unique name of the font. Any value is acceptable. The default value is an empty string.| 438| fullName | string | No| Yes| Font name. Any value is acceptable. The default value is an empty string.| 439| fontFamily | string | No| Yes| Family name of the font. Any value is acceptable. The default value is an empty string.| 440| fontSubfamily | string | No| Yes| Subfamily name of the font. Any value is acceptable. The default value is an empty string.| 441| weight | [FontWeight](#fontweight) | No| Yes| Font weight. The default value is the value of **FontWeight.W100**, that is, **0**. | 442| width | number | No| Yes| Font width. The value is an integer ranging from 1 to 9. The default value is **0**.| 443| 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**.| 444| 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**.| 445| symbolic | boolean | No| Yes| Whether the font is symbolic. The value **true** means that the font is symbolic, and **false** means the opposite.| 446 447## FontCollection 448 449Implements a font manager. 450 451### getGlobalInstance 452 453static getGlobalInstance(): FontCollection 454 455Obtains a global **FontCollection** instance. 456 457**System capability**: SystemCapability.Graphics.Drawing 458 459**Return value** 460 461| Type | Description | 462| ------ | ------------------ | 463| [FontCollection](#fontcollection) | **FontCollection** instance.| 464 465**Example** 466 467```ts 468import { text } from "@kit.ArkGraphics2D" 469 470function textFunc() { 471 let fontCollection = text.FontCollection.getGlobalInstance(); 472} 473 474@Entry 475@Component 476struct Index { 477 fun: Function = textFunc; 478 build() { 479 Column() { 480 Button().onClick(() => { 481 this.fun(); 482 }) 483 } 484 } 485} 486``` 487 488### loadFontSync 489 490loadFontSync(name: string, path: string | Resource): void 491 492Loads 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. 493 494**System capability**: SystemCapability.Graphics.Drawing 495 496**Parameters** 497 498| Name| Type | Mandatory| Description | 499| ----- | ------------------ | ---- | --------------------------------------------------------------------------------- | 500| name | string | Yes | Name of the font. | 501| 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*.| 502 503**Example** 504 505```ts 506import { text } from "@kit.ArkGraphics2D" 507 508let fontCollection: text.FontCollection = new text.FontCollection(); 509 510@Entry 511@Component 512struct RenderTest { 513 LoadFontSyncTest() { 514 fontCollection.loadFontSync('Clock_01', 'file:///system/fonts/HarmonyClock_01.ttf') 515 let fontFamilies: Array<string> = ["Clock_01"] 516 let myTextStyle: text.TextStyle = { 517 fontFamilies: fontFamilies 518 }; 519 let myParagraphStyle: text.ParagraphStyle = { 520 textStyle: myTextStyle, 521 } 522 let paragraphBuilder: text.ParagraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection); 523 524 let textData = "Test loadFontSync to load the font HarmonyClock_01.ttf." 525 paragraphBuilder.addText(textData); 526 let paragraph: text.Paragraph = paragraphBuilder.build(); 527 paragraph.layoutSync(600); 528 } 529 530 aboutToAppear() { 531 this.LoadFontSyncTest(); 532 } 533 534 build() { 535 } 536} 537``` 538 539### clearCaches 540 541clearCaches(): void 542 543Clears the font cache. 544 545The font cache has a memory limit and a clearing mechanism. It occupies limited memory. You are not advised to clear it unless otherwise required. 546 547**System capability**: SystemCapability.Graphics.Drawing 548 549**Example** 550 551```ts 552import { text } from "@kit.ArkGraphics2D" 553 554@Entry 555@Component 556struct Index { 557 build() { 558 Column() { 559 Button().onClick(() => { 560 text.FontCollection.getGlobalInstance().clearCaches(); 561 }) 562 } 563 } 564} 565``` 566 567## ParagraphStyle 568 569Describes a paragraph style. 570 571**System capability**: SystemCapability.Graphics.Drawing 572 573| Name | Type | Read Only| Optional| Description | 574| -------------------- | ------------------------------------------ | ---- | ---- | -------------------------------------------- | 575| textStyle | [TextStyle](#textstyle) | Yes | Yes | Text style applied to the paragraph. The default value is the initial text style.| 576| textDirection | [TextDirection](#textdirection) | Yes | Yes | Text direction. The default value is **LTR**. | 577| 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.| 578| wordBreak | [WordBreak](#wordbreak) | Yes | Yes | Word break type. The default value is **BREAK_WORD**. | 579| maxLines | number | Yes | Yes | Maximum number of lines. The value is an integer. The default value is **1e9**. | 580| breakStrategy | [BreakStrategy](#breakstrategy) | Yes | Yes | Text break strategy. The default value is **GREEDY**. | 581| strutStyle | [StrutStyle](#strutstyle) | Yes | Yes | Strut style. The default value is the initial **StrutStyle** object. | 582| textHeightBehavior | [TextHeightBehavior](#textheightbehavior) | Yes | Yes | Text height modifier pattern. The default value is **ALL**. | 583 584 585## PlaceholderAlignment 586 587Enumerates the vertical alignment modes of a placeholder relative to the surrounding text. 588 589**System capability**: SystemCapability.Graphics.Drawing 590 591| Name | Value| Description | 592| ------------------- | - | ---------------------- | 593| OFFSET_AT_BASELINE | 0 | Aligns the baseline of the placeholder to the baseline of the text. | 594| ABOVE_BASELINE | 1 | Aligns the bottom edge of the placeholder to the baseline of the text. | 595| BELOW_BASELINE | 2 | Aligns the top edge of the placeholder to the baseline of the text. | 596| TOP_OF_ROW_BOX | 3 | Aligns the top edge of the placeholder to the bottom edge of the text. | 597| BOTTOM_OF_ROW_BOX | 4 | Aligns the bottom edge of the placeholder to the bottom edge of the text. | 598| CENTER_OF_ROW_BOX | 5 | Aligns the middle of the placeholder to the middle of the text.| 599 600 601 602> **NOTE** 603> 604> 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. 605> 606> 607 608## PlaceholderSpan 609 610Describes the carrier of a placeholder style. 611 612**System capability**: SystemCapability.Graphics.Drawing 613 614| Name | Type | Read Only| Optional| Description | 615| -------------- | --------------------------------------------- | ---- | --- | --------------------------- | 616| width | number | Yes | No | Width of the placeholder, in units of px. The value is a floating point number.| 617| height | number | Yes | No | Height of the placeholder, in units of px. The value is a floating point number.| 618| align | [PlaceholderAlignment](#placeholderalignment) | Yes | No | Vertical alignment of the placeholder relative to the surrounding text.| 619| baseline | [TextBaseline](#textbaseline) | Yes | No | Type of the text baseline. | 620| baselineOffset | number | Yes | No | Offset to the text baseline, in units of px. The value is a floating point number. | 621 622## Range 623 624Describes a left-closed and right-open interval. 625 626**System capability**: SystemCapability.Graphics.Drawing 627 628| Name | Type | Read Only| Optional| Description | 629| ----- | ------ | ---- | --- | --------------- | 630| start | number | Yes | No | Index of the leftmost point of the interval. The value is an integer.| 631| end | number | Yes | No | Index of the rightmost point of the interval. The value is an integer.| 632 633## Paragraph 634 635Implements a carrier that stores the text content and style. You can perform operations such as typography and drawing. 636 637Before calling any of the following APIs, you must use [build()](#build) of the [ParagraphBuilder](#paragraphbuilder) class to create a **Paragraph** object. 638 639### layoutSync 640 641layoutSync(width: number): void 642 643Performs typography and calculates the positions of all glyphs. 644 645**System capability**: SystemCapability.Graphics.Drawing 646 647**Parameters** 648 649| Name| Type | Mandatory| Description | 650| ----- | ------ | ---- | -------------- | 651| width | number | Yes | Maximum width of a single line, in units of px. The value is a floating point number.| 652 653**Example** 654 655```ts 656paragraph.layoutSync(100); 657``` 658 659### paint 660 661paint(canvas: drawing.Canvas, x: number, y: number): void 662 663Paints the text on the canvas with the coordinate point (x, y) as the upper left corner. 664 665**System capability**: SystemCapability.Graphics.Drawing 666 667**Parameters** 668 669| Name| Type | Mandatory| Description | 670| ------ | ---------------------------------------------------- | ---- | ---------------------- | 671| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | Yes | Target canvas. | 672| x | number | Yes | X coordinate of the upper left corner. The value is a floating point number.| 673| y | number | Yes | Y coordinate of the upper left corner. The value is a floating point number.| 674 675**Example** 676 677```ts 678const color: ArrayBuffer = new ArrayBuffer(160000); 679let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } } 680let pixelMap: image.PixelMap = image.createPixelMapSync(color, opts); 681let canvas = new drawing.Canvas(pixelMap); 682paragraph.paint(canvas, 0, 0); 683``` 684 685### paintOnPath 686 687paintOnPath(canvas: drawing.Canvas, path: drawing.Path, hOffset: number, vOffset: number): void 688 689Draws text along a path on the canvas. 690 691**System capability**: SystemCapability.Graphics.Drawing 692 693**Parameters** 694 695| Name| Type | Mandatory| Description | 696| ------ | ---------------------------------------------------- | ---- | ---------------------- | 697| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | Yes | Target canvas. | 698| path | [drawing.Path](js-apis-graphics-drawing.md#path) | Yes | Path along which the text is drawn. | 699| 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.| 700| 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.| 701 702**Example** 703 704```ts 705const color: ArrayBuffer = new ArrayBuffer(160000); 706let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } } 707let pixelMap: image.PixelMap = image.createPixelMapSync(color, opts); 708let canvas = new drawing.Canvas(pixelMap); 709let path = new drawing.Path(); 710path.arcTo(20, 20, 180, 180, 180, 90); 711paragraph.paintOnPath(canvas, path, 0, 0); 712``` 713 714### getMaxWidth 715 716getMaxWidth(): number 717 718Obtains the maximum width of the line in the text. 719 720**System capability**: SystemCapability.Graphics.Drawing 721 722**Return value** 723 724| Type | Description | 725| ------ | --------- | 726| number | Maximum line width, in units of px. The value is a floating point number.| 727 728**Example** 729 730```ts 731let maxWidth = paragraph.getMaxWidth(); 732``` 733 734### getHeight 735 736getHeight(): number 737 738Obtains the total height of the text. 739 740**System capability**: SystemCapability.Graphics.Drawing 741 742**Return value** 743 744| Type | Description | 745| ------ | ----- | 746| number | Total height, in units of px. The value is a floating point number.| 747 748**Example** 749 750```ts 751let height = paragraph.getHeight(); 752``` 753 754### getLongestLine 755 756getLongestLine(): number 757 758Obtains the longest line in the text. 759 760**System capability**: SystemCapability.Graphics.Drawing 761 762**Return value** 763 764| Type | Description | 765| ------ | ------------- | 766| number | Longest line, in units of px. The value is a floating point number.| 767 768**Example** 769 770```ts 771let longestLine = paragraph.getLongestLine(); 772``` 773 774### getLongestLineWithIndent<sup>13+</sup> 775 776getLongestLineWithIndent(): number 777 778Obtains 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. 779 780**System capability**: SystemCapability.Graphics.Drawing 781 782**Return value** 783 784| Type | Description | 785| ------ | ------------- | 786| number | Width of the longest line, including its indentation. The value is a floating point number, in px.| 787 788**Example** 789 790```ts 791let longestLineWithIndent = paragraph.getLongestLineWithIndent(); 792``` 793 794### getMinIntrinsicWidth 795 796getMinIntrinsicWidth(): number 797 798Obtains the minimum intrinsic width of the paragraph. 799 800**System capability**: SystemCapability.Graphics.Drawing 801 802**Return value** 803 804| Type | Description | 805| ------ | ----------------------------- | 806| number | Minimum intrinsic width, in units of px. The value is a floating point number.| 807 808**Example** 809 810```ts 811let minIntrinsicWidth = paragraph.getMinIntrinsicWidth(); 812``` 813 814### getMaxIntrinsicWidth 815 816getMaxIntrinsicWidth(): number 817 818Obtains the maximum intrinsic width of the paragraph. 819 820**System capability**: SystemCapability.Graphics.Drawing 821 822**Return value** 823 824| Type | Description | 825| ------ | ----------------------------- | 826| number | Maximum intrinsic width, in units of px. The value is a floating point number.| 827 828**Example** 829 830```ts 831let maxIntrinsicWidth = paragraph.getMaxIntrinsicWidth(); 832``` 833 834### getAlphabeticBaseline 835 836getAlphabeticBaseline(): number 837 838Obtains the alphabetic baseline. 839 840**System capability**: SystemCapability.Graphics.Drawing 841 842**Return value** 843 844| Type | Description | 845| ------ | ------------------ | 846| number | Alphabetic baseline, in units of px. The value is a floating point number.| 847 848**Example** 849 850```ts 851let alphabeticBaseline = paragraph.getAlphabeticBaseline(); 852``` 853 854### getIdeographicBaseline 855 856getIdeographicBaseline(): number 857 858Obtains the ideographic baseline. 859 860**System capability**: SystemCapability.Graphics.Drawing 861 862**Return value** 863 864| Type | Description | 865| ------ | -------------------- | 866| number | Ideographic baseline, in units of px. The value is a floating point number.| 867 868**Example** 869 870```ts 871let ideographicBaseline = paragraph.getIdeographicBaseline(); 872``` 873 874### getRectsForRange 875 876getRectsForRange(range: Range, widthStyle: RectWidthStyle, heightStyle: RectHeightStyle): Array\<TextBox> 877 878Obtains the rectangles occupied by the characters in the range of the text under the given rectangle width and height. 879 880**System capability**: SystemCapability.Graphics.Drawing 881 882**Parameters** 883 884| Name | Type | Mandatory| Description | 885| ----------- | ----------------------------------- | ---- | ------------------------ | 886| range | [Range](#range) | Yes | Range of the text. | 887| widthStyle | [RectWidthStyle](#rectwidthstyle) | Yes | Width of the rectangle.| 888| heightStyle | [RectHeightStyle](#rectheightstyle) | Yes | Height of the rectangle.| 889 890**Return value** 891 892| Type | Description | 893| --------------------------- | ----------- | 894| Array\<[TextBox](#textbox)> | Array holding the rectangles obtained.| 895 896**Example** 897 898```ts 899let range: text.Range = { start: 0, end: 1}; 900let rects = paragraph.getRectsForRange(range, text.RectWidthStyle.TIGHT, text.RectHeightStyle.TIGHT); 901``` 902 903### getRectsForPlaceholders 904 905getRectsForPlaceholders(): Array\<TextBox> 906 907Obtains the rectangles occupied by all placeholders in the text. 908 909**System capability**: SystemCapability.Graphics.Drawing 910 911**Return value** 912 913| Type | Description | 914| --------------------------- | ----------- | 915| Array\<[TextBox](#textbox)> | Array holding the rectangles obtained.| 916 917**Example** 918 919```ts 920let placeholderRects = paragraph.getRectsForPlaceholders(); 921``` 922 923### getGlyphPositionAtCoordinate 924 925getGlyphPositionAtCoordinate(x: number, y: number): PositionWithAffinity 926 927Obtains the position of a glyph close to a given coordinate. 928 929**System capability**: SystemCapability.Graphics.Drawing 930 931**Parameters** 932 933| Name| Type | Mandatory| Description | 934| ----- | ------ | ---- | ------ | 935| x | number | Yes | X coordinate. The value is a floating point number.| 936| y | number | Yes | Y coordinate. The value is a floating point number.| 937 938**Return value** 939 940| Type | Description | 941| --------------------------------------------- | ----------- | 942| [PositionWithAffinity](#positionwithaffinity) | Position of the glyph.| 943 944**Example** 945 946```ts 947let positionWithAffinity = paragraph.getGlyphPositionAtCoordinate(0, 0); 948``` 949 950### getWordBoundary 951 952getWordBoundary(offset: number): Range 953 954Obtains the range of the word where the glyph with a given offset is located. 955 956**System capability**: SystemCapability.Graphics.Drawing 957 958**Parameters** 959 960| Name| Type | Mandatory| Description | 961| ------ | ------ | ---- | ----------- | 962| offset | number | Yes | Offset of the glyph. The value is an integer.| 963 964**Return value** 965 966| Type | Description | 967| --------------- | -------------- | 968| [Range](#range) | Range of the word.| 969 970**Example** 971 972```ts 973let wordRange = paragraph.getWordBoundary(0); 974``` 975 976### getLineCount 977 978getLineCount(): number 979 980Obtains the number of text lines. 981 982**System capability**: SystemCapability.Graphics.Drawing 983 984**Return value** 985 986| Type | Description | 987| ------ | --------- | 988| number | Number of text lines. The value is an integer.| 989 990**Example** 991 992```ts 993let lineCount = paragraph.getLineCount(); 994``` 995 996### getLineHeight 997 998getLineHeight(line: number): number 999 1000Obtains the height of a given line. 1001 1002**System capability**: SystemCapability.Graphics.Drawing 1003 1004**Parameters** 1005 1006| Name| Type | Mandatory| Description | 1007| ----- | ------ | ---- | --------- | 1008| line | number | Yes | Index of the line. The value is an integer.| 1009 1010**Return value** 1011 1012| Type | Description | 1013| ------ | ---- | 1014| number | Line height.| 1015 1016**Example** 1017 1018```ts 1019let lineHeight = paragraph.getLineHeight(0); 1020``` 1021 1022### getLineWidth 1023 1024getLineWidth(line: number): number 1025 1026Obtains the width of a given line. 1027 1028**System capability**: SystemCapability.Graphics.Drawing 1029 1030**Parameters** 1031 1032| Name| Type | Mandatory| Description | 1033| ----- | ------ | ---- | --------- | 1034| line | number | Yes | Index of the line. The value is an integer.| 1035 1036**Return value** 1037 1038| Type | Description | 1039| ------ | ---- | 1040| number | Line width.| 1041 1042**Example** 1043 1044```ts 1045let lineWidth = paragraph.getLineWidth(0); 1046``` 1047 1048### didExceedMaxLines 1049 1050didExceedMaxLines(): boolean 1051 1052Checks whether the number of lines in the paragraph exceeds the maximum. 1053 1054**System capability**: SystemCapability.Graphics.Drawing 1055 1056**Return value** 1057 1058| Type | Description | 1059| ------- | -------------------------------------------------------- | 1060| boolean | **true**: The number of lines exceeds the maximum.<br>**false**: The number of lines does not exceed the maximum.| 1061 1062**Example** 1063 1064```ts 1065let didExceed = paragraph.didExceedMaxLines(); 1066``` 1067 1068### getTextLines 1069 1070getTextLines(): Array\<TextLine> 1071 1072Obtains all the text lines. 1073 1074**System capability**: SystemCapability.Graphics.Drawing 1075 1076**Return value** 1077 1078| Type | Description | 1079| ----------------------------- | ------------- | 1080| Array\<[TextLine](#textline)> | Array of text lines.| 1081 1082**Example** 1083 1084```ts 1085let lines = paragraph.getTextLines(); 1086``` 1087 1088### getActualTextRange 1089 1090getActualTextRange(lineNumber: number, includeSpaces: boolean): Range 1091 1092Obtains the actually visible text range in the specified line, excluding the ellipsis displayed due to text overflow. 1093 1094**System capability**: SystemCapability.Graphics.Drawing 1095 1096**Parameters** 1097 1098| Name| Type | Mandatory| Description | 1099| ----- | ------ | ---- | --------- | 1100| lineNumber | number | Yes | Line number of the text range, starting from 0.| 1101| includeSpaces | boolean | Yes | Whether spaces are included. The value **true** means that spaces are contained, and **false** means the opposite.| 1102 1103**Return value** 1104 1105| Type | Description | 1106| ---------------- | ------------------------------------------------ | 1107| [Range](#range) | Text range obtained. | 1108 1109**Example** 1110 1111```ts 1112let rang = paragraph.getActualTextRange(0, true); 1113``` 1114 1115 1116### getLineMetrics 1117 1118getLineMetrics(): Array\<LineMetrics> 1119 1120Obtains an array of line measurement information. 1121 1122**System capability**: SystemCapability.Graphics.Drawing 1123 1124**Return value** 1125 1126| Type | Description | 1127| ----------------------------- | ------------- | 1128| Array\<[LineMetrics](#linemetrics)> | Array of line measurement information.| 1129 1130**Example** 1131 1132```ts 1133let arrLineMetrc = paragraph.getLineMetrics(); 1134``` 1135 1136### getLineMetrics 1137 1138getLineMetrics(lineNumber: number): LineMetrics | undefined 1139 1140Obtains the line measurement information of a line. 1141 1142**System capability**: SystemCapability.Graphics.Drawing 1143 1144**Parameters** 1145 1146| Name| Type | Mandatory| Description | 1147| ----- | ------ | ---- | --------- | 1148| lineNumber | number | Yes | Line number, starting from 0.| 1149 1150**Return value** 1151 1152| Type | Description | 1153| ---------------- | ------------------------------------------------ | 1154| [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. | 1155 1156**Example** 1157 1158```ts 1159let lineMetrics = paragraph.getLineMetrics(0); 1160``` 1161 1162## RunMetrics 1163 1164Describes the layout information and measurement information of a run of text in a text line. 1165 1166**System capability**: SystemCapability.Graphics.Drawing 1167 1168| Name | Type | Read Only| Optional| Description | 1169| --------- | -------------------------------------------------- | ---- | ---- | ----------- | 1170| textStyle | [TextStyle](#textstyle) | Yes | No | Text style.| 1171| fontMetrics | [drawing.FontMetrics](js-apis-graphics-drawing.md#fontmetrics)| Yes | No | Font measurement information. | 1172 1173## LineMetrics 1174 1175Describes the measurement information of a single line of text in the text layout. 1176 1177**System capability**: SystemCapability.Graphics.Drawing 1178 1179| Name | Type | Read Only| Optional| Description | 1180| --------- | -------------------------------------------------- | ---- | ---- | ----------- | 1181| startIndex | number | Yes | No | Start index of the line in the text buffer.| 1182| endIndex | number | Yes | No | End index of the line in the text buffer.| 1183| ascent | number | Yes | No | Ascent, that is, the distance from the baseline to the top of the character.| 1184| descent | number | Yes | No | Descent, that is, the distance from the baseline to the bottom of the character.| 1185| height | number | Yes | No | Height of the line, which is Math.round(ascent + descent).| 1186| width | number | Yes | No | Width of the line. | 1187| left | number | Yes | No | Left edge of the line. The right edge is the value of **left** plus the value of **width**.| 1188| baseline | number | Yes | No | Y coordinate of the baseline in the line relative to the top of the paragraph.| 1189| lineNumber | number | Yes | No | Line number, starting from 0.| 1190| topHeight | number | Yes | No | Height from the top to the current line.| 1191| runMetrics | Map<number, [RunMetrics](#runmetrics)> | Yes | No | Mapping between the text index range and the associated font measurement information.| 1192 1193## TextBox 1194 1195Describes the rectangle that holds the text. 1196 1197**System capability**: SystemCapability.Graphics.Drawing 1198 1199| Name | Type | Read Only| Optional| Description | 1200| --------- | -------------------------------------------------- | ---- | ---- | ----------- | 1201| rect | [common2D.Rect](js-apis-graphics-common2D.md#rect) | Yes | No | Information about the rectangle.| 1202| direction | [TextDirection](#textdirection) | Yes | No | Text direction. | 1203 1204## PositionWithAffinity 1205 1206Describes the position and affinity of a glyph. 1207 1208**System capability**: SystemCapability.Graphics.Drawing 1209 1210| Name | Type | Read Only| Optional| Description | 1211| --------- | --------------------- | ---- | ---- | ------------------------ | 1212| position | number | Yes | No | Index of the glyph relative to the paragraph. The value is an integer. | 1213| affinity | [Affinity](#affinity) | Yes | No | Affinity of the position. | 1214 1215## RectWidthStyle 1216 1217Enumerates the rectangle width styles. 1218 1219**System capability**: SystemCapability.Graphics.Drawing 1220 1221| Name | Value| Description | 1222| ----- | - | -------------------------------------- | 1223| 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. | 1224| MAX | 1 | The rectangle's width is extended to align with the widest rectangle across all lines. | 1225 1226## RectHeightStyle 1227 1228Enumerates the rectangle height styles. 1229 1230**System capability**: SystemCapability.Graphics.Drawing 1231 1232| Name | Value| Description | 1233| ------------------------- | - | ---------------------------------------------- | 1234| TIGHT | 0 | Tight style. | 1235| MAX | 1 | Extends the height to match the highest rectangle in all lines. | 1236| INCLUDE_LINE_SPACE_MIDDLE | 2 | Includes half of the line spacing to both the top and bottom of the rectangle.| 1237| INCLUDE_LINE_SPACE_TOP | 3 | Includes the line spacing to the top of the rectangle. | 1238| INCLUDE_LINE_SPACE_BOTTOM | 4 | Includes the line spacing to the bottom of the rectangle. | 1239| STRUT | 5 | Sets the height according to the strut style. | 1240 1241## Affinity 1242 1243Enumerates the affinity modes. 1244 1245**System capability**: SystemCapability.Graphics.Drawing 1246 1247| Name | Value| Description | 1248| ---------- | - | ----------------------------- | 1249| UPSTREAM | 0 | The position has affinity for the upstream side of the text position.| 1250| DOWNSTREAM | 1 | The position has affinity for the downstream side of the text position.| 1251 1252## ParagraphBuilder 1253 1254Implements a paragraph builder. 1255 1256### constructor 1257 1258constructor(paragraphStyle: ParagraphStyle, fontCollection: FontCollection) 1259 1260A constructor used to create a **ParagraphBuilder** object. 1261 1262**System capability**: SystemCapability.Graphics.Drawing 1263 1264**Parameters** 1265 1266| Name | Type | Mandatory| Description | 1267| -------------- | --------------------------------- | ---- | ----------- | 1268| paragraphStyle | [ParagraphStyle](#paragraphstyle) | Yes | Paragraph style. | 1269| fontCollection | [FontCollection](#fontcollection) | Yes | Font manager.| 1270 1271**Example** 1272 1273```ts 1274import { text } from "@kit.ArkGraphics2D"; 1275 1276function textFunc() { 1277 let myTextStyle: text.TextStyle = { 1278 color: { alpha: 255, red: 255, green: 0, blue: 0 }, 1279 fontSize: 33, 1280 }; 1281 let myParagraphStyle: text.ParagraphStyle = { 1282 textStyle: myTextStyle, 1283 align: text.TextAlign.END, 1284 }; 1285 let fontCollection = new text.FontCollection(); 1286 let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection); 1287} 1288 1289@Entry 1290@Component 1291struct Index { 1292 fun: Function = textFunc; 1293 build() { 1294 Column() { 1295 Button().onClick(() => { 1296 this.fun(); 1297 }) 1298 } 1299 } 1300} 1301``` 1302 1303### pushStyle 1304 1305 pushStyle(textStyle: TextStyle): void 1306 1307Pushes a text style. 1308 1309> **NOTE** 1310> 1311> This API pushes the style of the current text blob until [popStyle](#popstyle), which restores to the previous text style, is called. 1312 1313**System capability**: SystemCapability.Graphics.Drawing 1314 1315**Parameters** 1316 1317| Name | Type | Mandatory| Description | 1318| --------- | --------- | ---- | ------------------------------------------------------------------------------------------------------ | 1319| 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.| 1320 1321**Example** 1322 1323```ts 1324import { drawing } from '@kit.ArkGraphics2D' 1325import { text } from "@kit.ArkGraphics2D" 1326import { common2D } from "@kit.ArkGraphics2D" 1327import { image } from '@kit.ImageKit'; 1328 1329function textFunc() { 1330 let myTextStyle: text.TextStyle = { 1331 color: { alpha: 255, red: 255, green: 0, blue: 0 }, 1332 fontSize: 33, 1333 }; 1334 let myParagraphStyle: text.ParagraphStyle = { 1335 textStyle: myTextStyle, 1336 align: text.TextAlign.CENTER, 1337 }; 1338 let fontCollection = new text.FontCollection(); 1339 let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection); 1340 ParagraphGraphBuilder.pushStyle(myTextStyle); 1341} 1342 1343@Entry 1344@Component 1345struct Index { 1346 fun: Function = textFunc; 1347 build() { 1348 Column() { 1349 Button().onClick(() => { 1350 this.fun(); 1351 }) 1352 } 1353 } 1354} 1355``` 1356 1357### popStyle 1358 1359popStyle(): void 1360 1361Restores to the previous text style. 1362 1363**System capability**: SystemCapability.Graphics.Drawing 1364 1365**Example** 1366 1367```ts 1368import { drawing } from '@kit.ArkGraphics2D' 1369import { text } from "@kit.ArkGraphics2D" 1370import { common2D } from "@kit.ArkGraphics2D" 1371import { image } from '@kit.ImageKit'; 1372 1373function textFunc() { 1374 let myTextStyle: text.TextStyle = { 1375 color: { alpha: 255, red: 255, green: 0, blue: 0 }, 1376 fontSize: 33, 1377 }; 1378 let myParagraphStyle: text.ParagraphStyle = { 1379 textStyle: myTextStyle, 1380 align: text.TextAlign.END, 1381 }; 1382 let fontCollection = new text.FontCollection(); 1383 let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection); 1384 ParagraphGraphBuilder.pushStyle(myTextStyle); 1385 ParagraphGraphBuilder.popStyle(); 1386} 1387 1388@Entry 1389@Component 1390struct Index { 1391 fun: Function = textFunc; 1392 build() { 1393 Column() { 1394 Button().onClick(() => { 1395 this.fun(); 1396 }) 1397 } 1398 } 1399} 1400``` 1401 1402### addText 1403 1404addText(text: string): void 1405 1406Inserts a text string into the paragraph being built. 1407 1408**System capability**: SystemCapability.Graphics.Drawing 1409 1410**Parameters** 1411 1412| Name | Type | Mandatory| Description | 1413| ------- | ------- | ---- | -------------------------- | 1414| text | string | Yes | Text string to insert.| 1415 1416**Example** 1417 1418```ts 1419import { drawing } from '@kit.ArkGraphics2D' 1420import { text } from "@kit.ArkGraphics2D" 1421import { common2D } from "@kit.ArkGraphics2D" 1422import { image } from '@kit.ImageKit'; 1423 1424function textFunc() { 1425 let myTextStyle: text.TextStyle = { 1426 color: { alpha: 255, red: 255, green: 0, blue: 0 }, 1427 fontSize: 33, 1428 }; 1429 let myParagraphStyle: text.ParagraphStyle = { 1430 textStyle: myTextStyle, 1431 align: text.TextAlign.END, 1432 }; 1433 let fontCollection = new text.FontCollection(); 1434 let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection); 1435 ParagraphGraphBuilder.addText("123666"); 1436} 1437 1438@Entry 1439@Component 1440struct Index { 1441 fun: Function = textFunc; 1442 build() { 1443 Column() { 1444 Button().onClick(() => { 1445 this.fun(); 1446 }) 1447 } 1448 } 1449} 1450``` 1451 1452### addPlaceholder 1453 1454addPlaceholder(placeholderSpan: PlaceholderSpan): void 1455 1456Inserts a placeholder into the paragraph being built. 1457 1458**System capability**: SystemCapability.Graphics.Drawing 1459 1460**Parameters** 1461 1462| Name | Type | Mandatory| Description | 1463| --------------- | ----------------------------------- | ---- | --------------------------------------------------- | 1464| placeholderSpan | [PlaceholderSpan](#placeholderspan) | Yes | Placeholder span, which describes the size, alignment, baseline type, and baseline offset of the placeholder. | 1465 1466**Example** 1467 1468```ts 1469import { drawing } from '@kit.ArkGraphics2D' 1470import { text } from "@kit.ArkGraphics2D" 1471import { common2D } from "@kit.ArkGraphics2D" 1472import { image } from '@kit.ImageKit'; 1473 1474function textFunc() { 1475 let myParagraphStyle: text.ParagraphStyle = { 1476 align: text.TextAlign.END, 1477 }; 1478 let myPlaceholderSpan: text.PlaceholderSpan = { 1479 width: 10000, 1480 height: 10000000, 1481 align: text.PlaceholderAlignment.ABOVE_BASELINE, 1482 baseline: text.TextBaseline.ALPHABETIC, 1483 baselineOffset: 100000 1484 }; 1485 let fontCollection = new text.FontCollection(); 1486 let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection); 1487 ParagraphGraphBuilder.addPlaceholder(myPlaceholderSpan); 1488} 1489 1490@Entry 1491@Component 1492struct Index { 1493 fun: Function = textFunc; 1494 build() { 1495 Column() { 1496 Button().onClick(() => { 1497 this.fun(); 1498 }) 1499 } 1500 } 1501} 1502``` 1503 1504### build 1505 1506build(): Paragraph 1507 1508Creates a paragraph object that can be used for subsequent typography and rendering. 1509 1510**System capability**: SystemCapability.Graphics.Drawing 1511 1512**Return value** 1513 1514| Type | Description | 1515| ------------------------ | ------------------------------ | 1516| [Paragraph](#paragraph) | **Paragraph** object that can be used for subsequent typography and rendering.| 1517 1518**Example** 1519 1520```ts 1521import { drawing, text, common2D } from '@kit.ArkGraphics2D' 1522import { image } from '@kit.ImageKit'; 1523 1524function textFunc() { 1525 let myTextStyle: text.TextStyle = { 1526 color : {alpha: 255, red: 255, green: 0, blue: 0}, 1527 fontSize : 20, 1528 }; 1529 let myParagraphStyle: text.ParagraphStyle = { 1530 textStyle : myTextStyle, 1531 }; 1532 let fontCollection = new text.FontCollection(); 1533 let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection); 1534 ParagraphGraphBuilder.addText("123456789"); 1535 let paragraph = ParagraphGraphBuilder.build(); 1536 paragraph.layoutSync(200); 1537} 1538 1539@Entry 1540@Component 1541struct Index { 1542 fun: Function = textFunc; 1543 build() { 1544 Column() { 1545 Button().onClick(() => { 1546 this.fun(); 1547 }) 1548 } 1549 } 1550} 1551``` 1552 1553### addSymbol 1554 1555addSymbol(symbolId: number): void 1556 1557Inserts a symbol into the paragraph being built. 1558 1559**System capability**: SystemCapability.Graphics.Drawing 1560 1561**Parameters** 1562 1563| Name | Type | Mandatory| Description | 1564| -------- | ------- | ---- | ----------------------------------------------------------- | 1565| 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 and symbol names, see the **value** and **name** fields in the [JSON file](https://gitee.com/openharmony/global_system_resources/blob/master/systemres/main/resources/base/element/symbol.json).| 1566 1567**Example** 1568 1569```ts 1570import { text } from "@kit.ArkGraphics2D"; 1571 1572function textFunc() { 1573 let myTextStyle: text.TextStyle = { 1574 color: { alpha: 255, red: 255, green: 0, blue: 0 }, 1575 fontSize: 33, 1576 }; 1577 let myParagraphStyle: text.ParagraphStyle = { 1578 textStyle: myTextStyle, 1579 align: text.TextAlign.END, 1580 }; 1581 let fontCollection = new text.FontCollection(); 1582 let ParagraphGraphBuilder = new text.ParagraphBuilder(myParagraphStyle, fontCollection); 1583 ParagraphGraphBuilder.addSymbol(0xF0000); 1584 let paragraph = ParagraphGraphBuilder.build(); 1585} 1586 1587@Entry 1588@Component 1589struct Index { 1590 fun: Function = textFunc; 1591 build() { 1592 Column() { 1593 Button().onClick(() => { 1594 this.fun(); 1595 }) 1596 } 1597 } 1598} 1599``` 1600 1601## TextLine 1602 1603Implements a carrier that describes the basic text line structure of a paragraph. 1604 1605Before calling any of the following APIs, you must use [getTextLines ()](#gettextlines) of the [Paragraph](#paragraph) class to create a **TextLine** object. 1606### getGlyphCount 1607 1608getGlyphCount(): number 1609 1610Obtains the number of glyphs in this text line. 1611 1612**System capability**: SystemCapability.Graphics.Drawing 1613 1614**Return value** 1615 1616| Type | Description | 1617| ------- | ------------------ | 1618| number | Number of glyphs. The value is an integer.| 1619 1620**Example** 1621 1622```ts 1623import { text } from "@kit.ArkGraphics2D" 1624 1625function textFunc() { 1626 let GlyphCount = lines[0].getGlyphCount(); 1627} 1628 1629@Entry 1630@Component 1631struct Index { 1632 fun: Function = textFunc; 1633 build() { 1634 Column() { 1635 Button().onClick(() => { 1636 this.fun(); 1637 }) 1638 } 1639 } 1640} 1641``` 1642 1643### getTextRange 1644 1645getTextRange(): Range 1646 1647Obtains the range of the text in this text line in the entire paragraph. 1648 1649**System capability**: SystemCapability.Graphics.Drawing 1650 1651**Return value** 1652 1653| Type | Description | 1654| ---------------- | ------------------------------------------------ | 1655| [Range](#range) | Range of the text in this text line in the entire paragraph.| 1656 1657**Example** 1658 1659```ts 1660import { text } from "@kit.ArkGraphics2D" 1661 1662function textFunc() { 1663 let textRange = lines[0].getTextRange(); 1664} 1665 1666@Entry 1667@Component 1668struct Index { 1669 fun: Function = textFunc; 1670 build() { 1671 Column() { 1672 Button().onClick(() => { 1673 this.fun(); 1674 }) 1675 } 1676 } 1677} 1678``` 1679 1680### getGlyphRuns 1681 1682getGlyphRuns(): Array\<Run> 1683 1684Obtains the runs in this text line. 1685 1686**System capability**: SystemCapability.Graphics.Drawing 1687 1688**Return value** 1689 1690| Type | Description | 1691| ------------ | --------------------------- | 1692| Array\<[Run](#run)> | Array of the runs obtained.| 1693 1694**Example** 1695 1696```ts 1697import { text } from "@kit.ArkGraphics2D" 1698 1699function textFunc() { 1700 let runs = lines[0].getGlyphRuns(); 1701} 1702 1703@Entry 1704@Component 1705struct Index { 1706 fun: Function = textFunc; 1707 build() { 1708 Column() { 1709 Button().onClick(() => { 1710 this.fun(); 1711 }) 1712 } 1713 } 1714} 1715``` 1716 1717### paint 1718 1719paint(canvas: drawing.Canvas, x: number, y: number): void 1720 1721Paints this text line on the canvas with the coordinate point (x, y) as the upper left corner. 1722 1723**System capability**: SystemCapability.Graphics.Drawing 1724 1725**Parameters** 1726 1727| Name| Type | Mandatory| Description | 1728| ------ | ---------------------------------------------------- | ---- | ---------------------- | 1729| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | Yes | Target canvas. | 1730| x | number | Yes | X coordinate of the upper left corner. The value is a floating point number.| 1731| y | number | Yes | Y coordinate of the upper left corner. The value is a floating point number.| 1732 1733**Example** 1734 1735```ts 1736import { drawing } from '@kit.ArkGraphics2D' 1737import { text } from "@kit.ArkGraphics2D" 1738import { common2D } from "@kit.ArkGraphics2D" 1739import { image } from '@kit.ImageKit'; 1740 1741function textFunc(pixelmap: PixelMap) { 1742 let canvas = new drawing.Canvas(pixelmap); 1743 lines[0].paint(canvas, 0, 0); 1744} 1745 1746@Entry 1747@Component 1748struct Index { 1749 @State pixelmap?: PixelMap = undefined; 1750 fun: Function = textFunc; 1751 build() { 1752 Column() { 1753 Image(this.pixelmap).width(200).height(200); 1754 Button().onClick(() => { 1755 if (this.pixelmap == undefined) { 1756 const color: ArrayBuffer = new ArrayBuffer(160000); 1757 let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } } 1758 this.pixelmap = image.createPixelMapSync(color, opts); 1759 } 1760 this.fun(this.pixelmap); 1761 }) 1762 } 1763 } 1764} 1765``` 1766 1767## Run 1768 1769Implements a rendering unit for text typesetting. 1770 1771Before calling any of the following APIs, you must use [getGlyphRuns()](#getglyphruns) of the [TextLine](#textline) class to create a **Run** object. 1772 1773### getGlyphCount 1774 1775getGlyphCount(): number 1776 1777Obtains the number of glyphs in this run. 1778 1779**System capability**: SystemCapability.Graphics.Drawing 1780 1781**Return value** 1782 1783| Type | Description | 1784| ------- | -------------------- | 1785| number | Number of glyphs. The value is an integer.| 1786 1787**Example** 1788 1789```ts 1790import { text } from "@kit.ArkGraphics2D" 1791 1792function textFunc() { 1793 let glyphs = runs[0].getGlyphCount(); 1794} 1795 1796@Entry 1797@Component 1798struct Index { 1799 fun: Function = textFunc; 1800 build() { 1801 Column() { 1802 Button().onClick(() => { 1803 this.fun(); 1804 }) 1805 } 1806 } 1807} 1808``` 1809 1810### getGlyphs 1811 1812getGlyphs(): Array\<number> 1813 1814Obtains the index of each glyph in this run. 1815 1816**System capability**: SystemCapability.Graphics.Drawing 1817 1818**Return value** 1819 1820| Type | Description | 1821| --------------- | -------------------------------- | 1822| Array\<number> | Array holding the index of each glyph in the run.| 1823 1824**Example** 1825 1826```ts 1827import { text } from "@kit.ArkGraphics2D" 1828 1829function textFunc() { 1830 let glyph = runs[0].getGlyphs(); 1831} 1832 1833@Entry 1834@Component 1835struct Index { 1836 fun: Function = textFunc; 1837 build() { 1838 Column() { 1839 Button().onClick(() => { 1840 this.fun(); 1841 }) 1842 } 1843 } 1844} 1845``` 1846 1847### getPositions 1848 1849getPositions(): Array<common2D.Point> 1850 1851Obtains the position of each glyph relative to the respective line in this run. 1852 1853**System capability**: SystemCapability.Graphics.Drawing 1854 1855**Return value** 1856 1857| Type | Description | 1858| ---------------------- | ------------------------------------- | 1859| Array<[common2D.Point](js-apis-graphics-common2D.md#point12)> | Array holding the position of each glyph relative to the respective line in the run.| 1860 1861**Example** 1862 1863```ts 1864import { text } from "@kit.ArkGraphics2D"; 1865 1866function textFunc() { 1867 let positions = runs[0].getPositions (); // Obtain the positions of all glyphs in the run. 1868} 1869 1870@Entry 1871@Component 1872struct Index { 1873 fun: Function = textFunc; 1874 build() { 1875 Column() { 1876 Button().onClick(() => { 1877 this.fun(); 1878 }) 1879 } 1880 } 1881} 1882``` 1883 1884### getOffsets 1885 1886getOffsets(): Array<common2D.Point> 1887 1888Obtains the offset of each glyph in this run relative to its index. 1889 1890**System capability**: SystemCapability.Graphics.Drawing 1891 1892**Return value** 1893 1894| Type | Description | 1895| ---------------------- | -------------- | 1896| Array<[common2D.Point](js-apis-graphics-common2D.md#point12)> | Array holding the offset of each glyph in the run relative to its index.| 1897 1898**Example** 1899 1900```ts 1901import { text } from "@kit.ArkGraphics2D"; 1902 1903function textFunc() { 1904 let offsets = runs[0].getOffsets(); 1905} 1906 1907@Entry 1908@Component 1909struct Index { 1910 fun: Function = textFunc; 1911 build() { 1912 Column() { 1913 Button().onClick(() => { 1914 this.fun(); 1915 }) 1916 } 1917 } 1918} 1919``` 1920 1921### getFont 1922 1923getFont(): drawing.Font 1924 1925Obtains the **Font** object of this run. 1926 1927**System capability**: SystemCapability.Graphics.Drawing 1928 1929**Return value** 1930 1931| Type | Description | 1932| ------------------------------------------------- | -------------------------- | 1933| [drawing.Font](js-apis-graphics-drawing.md#font) | **Font** object of this run.| 1934 1935**Example** 1936 1937```ts 1938import { drawing } from '@kit.ArkGraphics2D' 1939import { text } from "@kit.ArkGraphics2D"; 1940 1941function textFunc() { 1942 let font = runs[0].getFont(); 1943} 1944 1945@Entry 1946@Component 1947struct Index { 1948 fun: Function = textFunc; 1949 build() { 1950 Column() { 1951 Button().onClick(() => { 1952 this.fun(); 1953 }) 1954 } 1955 } 1956} 1957``` 1958 1959### paint 1960 1961paint(canvas: drawing.Canvas, x: number, y: number): void 1962 1963Paints this run on the canvas with the coordinate point (x, y) as the upper left corner. 1964 1965**System capability**: SystemCapability.Graphics.Drawing 1966 1967**Parameters** 1968 1969| Name| Type | Mandatory| Description | 1970| ------ | ---------------------------------------------------- | ---- | ---------------------- | 1971| canvas | [drawing.Canvas](js-apis-graphics-drawing.md#canvas) | Yes | Target canvas. | 1972| x | number | Yes | X coordinate of the upper left corner. The value is a floating point number.| 1973| y | number | Yes | Y coordinate of the upper left corner. The value is a floating point number.| 1974 1975**Example** 1976 1977```ts 1978import { drawing } from '@kit.ArkGraphics2D' 1979import { text } from "@kit.ArkGraphics2D" 1980import { common2D } from "@kit.ArkGraphics2D" 1981import { image } from '@kit.ImageKit'; 1982 1983function textFunc() { 1984 const color: ArrayBuffer = new ArrayBuffer(160000); 1985 let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } } 1986 let pixelMap: image.PixelMap = image.createPixelMapSync(color, opts); 1987 let canvas = new drawing.Canvas(pixelMap); 1988 runs[0].paint(canvas, 0, 0); 1989} 1990 1991@Entry 1992@Component 1993struct Index { 1994 fun: Function = textFunc; 1995 build() { 1996 Column() { 1997 Button().onClick(() => { 1998 this.fun(); 1999 }) 2000 } 2001 } 2002} 2003``` 2004 2005## SystemFontType<sup>14+</sup> 2006 2007Enumerates the font types, which can be combined through bitwise OR operations. 2008 2009**System capability**: SystemCapability.Graphics.Drawing 2010 2011| Name| Value| Description| 2012| - | - | - | 2013| ALL | 1 << 0 | All font types, including the system font type, style font type, and user-installed font type.| 2014| GENERIC | 1 << 1 | System font type.| 2015| STYLISH | 1 << 2 | Style font type. The style font type is designed for 2-in-1 devices.| 2016| INSTALLED | 1 << 3 | Font type that has been installed.| 2017