1# Styled String 2 3Styled strings are string objects that facilitate the flexible application of text styles. 4 5> **NOTE** 6> 7> The initial APIs of this module are supported since API version 12. Updates will be marked with a superscript to indicate their earliest API version. 8> 9> Currently, styled strings cannot be used in worker threads. 10 11## Rules of Use 12 13* If a styled string conflicts with the current style settings in a component, the style set in the styled string takes effect. 14* If a styled string conflicts with the child components in [Text](./ts-basic-components-text.md), the style set in the styled string is applied to the **Text** component, and style settings of the child components, including [Span](./ts-basic-components-span.md), are ignored. 15* @State is not supported. 16 17## StyledString 18 19constructor(value: string | ImageAttachment | CustomSpan , styles?: Array\<StyleOptions>) 20 21**Atomic service API**: This API can be used in atomic services since API version 12. 22 23**Parameters** 24 25| Name| Type| Mandatory| Description| 26| -------- | -------- | -------- | -------- | 27| value | string \| [ImageAttachment](#imageattachment) \| [CustomSpan](#customspan) | Yes| Text of the styled string.<br>**NOTE**<br>If this parameter is of the ImageAttachment or CustomSpan type, the **styles** parameter does not take effect. | 28| styles | Array<[StyleOptions](#styleoptions)> | No| Initialization options of the styled string.<br>**NOTE**<br>If **start** is set to an invalid value, it uses the default value **0**.<br>If the value of **start** is valid but that of **length** is invalid, the difference between the length of the styled string and the value of **start** is used as the value of **length**.<br>If **StyledStringKey** does not match **StyledStringValue**, it does not take effect.<br>The **styledKey** parameter has no default value.| 29 30### Attributes 31 32**Atomic service API**: This API can be used in atomic services since API version 12. 33 34**System capability**: SystemCapability.ArkUI.ArkUI.Full 35 36| Name | Type | Read Only | Optional | Description | 37| ------ | ------ | ------ | ------ | -------------- | 38| length | number | Yes | No | Length of the styled string.<br>**NOTE**<br>If the styled string contains an image or a custom span, its length is 1.| 39 40### getString 41 42getString(): string 43 44Obtains the text of this styled string. 45 46**Atomic service API**: This API can be used in atomic services since API version 12. 47 48**System capability**: SystemCapability.ArkUI.ArkUI.Full 49 50**Return value** 51 52| Type |Description | 53| ------- | --------------------------------- | 54| string | Text of the styled string.<br>**NOTE**<br>If the styled string contains an image, the image is represented by a space in the return value.| 55 56### equals 57 58equals(other: StyledString): boolean 59 60Checks whether this styled string the same as another styled string. 61 62**Atomic service API**: This API can be used in atomic services since API version 12. 63 64**System capability**: SystemCapability.ArkUI.ArkUI.Full 65 66**Parameters** 67 68| Name | Type | Mandatory| Description | 69| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 70| other | [StyledString](#styledstring) | Yes | **StyledString** object to compare.| 71 72**Return value** 73 74| Type | Description | 75| ------- | --------------------------------- | 76| boolean | Whether two styled strings are equal.<br>**NOTE**<br>The two styled strings are the same if they have the same text and style.<br>**GestureStyle** in styled strings is not compared. This means that, if two styled strings are the same except for the event configured, they are the same.<br>In comparing **CustomSpan** objects, addresses are compared. The objects that have the same address are the same.| 77 78### subStyledString 79 80Obtains a substring of this styled string. 81 82subStyledString(start: number , length?: number): StyledString 83 84**Atomic service API**: This API can be used in atomic services since API version 12. 85 86**System capability**: SystemCapability.ArkUI.ArkUI.Full 87 88**Parameters** 89 90| Name | Type | Mandatory| Description | 91| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 92| start | number | Yes | Subscript that corresponds to the start position of the styled substring.| 93| length | number | No | Length of the styled substring.| 94 95**Return value** 96 97| Type | Description | 98| ------- | --------------------------------- | 99| [StyledString](#styledstring) | Styled substring.<br>**NOTE**<br>If the value of **start** is valid, the difference between the length of the styled string and the value of **start** is used as the default value of **length**.<br>If the values of **start** and **length** are out of the acceptable range or if any mandatory parameter is passed as **undefined**, an exception is thrown.| 100 101**Error codes** 102 103For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). 104 105| ID| Error Message| 106| ------- | -------- | 107| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | 108 109### getStyles 110 111Obtains the styles in the specified range of a styled string. 112 113getStyles(start: number , length: number , styledKey?: StyledStringKey): Array\<SpanStyle> 114 115**Atomic service API**: This API can be used in atomic services since API version 12. 116 117**System capability**: SystemCapability.ArkUI.ArkUI.Full 118 119**Parameters** 120 121| Name | Type | Mandatory| Description | 122| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 123| start | number | Yes | Subscript that corresponds to the target range in the styled string.| 124| length | number | Yes | Length of the target range in the styled string.| 125| styledKey | [StyledStringKey](#styledstringkey12) | No | Style key of the styled string.| 126 127**Return value** 128 129| Type | Description | 130| ------- | --------------------------------- | 131| Array<[SpanStyle](#spanstyle)> | Array of styles.<br>**NOTE**<br>If no style is set for the specified range in the styled string, an empty array is returned.<br>If the values of **start** and **length** are out of the acceptable range or if any mandatory parameter is passed as **undefined**, an exception is thrown.<br>If **styledKey** is set to an invalid value or **undefined**, an exception is thrown.<br>If **styledKey** is a **CustomSpan** object, the style returned is the one passed to create the object. That is, modifying the style object also affects the actual display effect.| 132 133**Error codes** 134 135For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). 136 137| ID| Error Message| 138| ------- | -------- | 139| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | 140 141### fromHtml 142 143Converts an HTML-formatted string into a styled string. Currently, the conversion supports the following HTML tags: **\<p>**, **Span**, **\<img>**. Only the styles defined by the **style** attributes of these tags can be converted into corresponding styles in styled strings. 144 145static fromHtml(html: string): Promise\<StyledString> 146 147**Atomic service API**: This API can be used in atomic services since API version 12. 148 149**System capability**: SystemCapability.ArkUI.ArkUI.Full 150 151**Parameters** 152 153| Name | Type | Mandatory| Description | 154| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 155| html | string | Yes | HTML-formatted string.| 156 157**Return value** 158 159| Type | Description | 160| ------- | --------------------------------- | 161| [StyledString](#styledstring) | Styled string.| 162 163**Error codes** 164 165For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). 166 167| ID| Error Message| 168| ------- | -------- | 169| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | 170 171## MutableStyledString 172 173Inherits from the [StyledString](#styledstring) class. 174 175> **An exception is thrown in the following cases:** 176> 177> The values of **start** and **length** are out of the acceptable range or if any mandatory parameter is passed as **undefined**. 178> 179> **styledKey** or **styledValue** is set to an invalid value or they do not match. 180> 181 182### replaceString 183 184Replaces the string in the specified range of this styled string. 185 186replaceString(start: number , length: number , other: string): void 187 188**Atomic service API**: This API can be used in atomic services since API version 12. 189 190**System capability**: SystemCapability.ArkUI.ArkUI.Full 191 192**Parameters** 193 194| Name | Type | Mandatory| Description | 195| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 196| start | number | Yes | Subscript of the target range.| 197| length | number | Yes | Length of the target range.| 198| other | string | Yes | String to replace the content in the target range.<br>**NOTE**<br>The string specified here uses the style of the character at the **start** position.| 199 200**Error codes** 201 202For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). 203 204| ID| Error Message| 205| ------- | -------- | 206| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | 207 208### insertString 209 210Inserts a string. 211 212insertString(start: number , other: string): void 213 214**Atomic service API**: This API can be used in atomic services since API version 12. 215 216**System capability**: SystemCapability.ArkUI.ArkUI.Full 217 218**Parameters** 219 220| Name | Type | Mandatory| Description | 221| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 222| start | number | Yes | Subscript of the position where the string will be inserted.| 223| other | string | Yes | String to insert.<br>**NOTE**<br>The string specified here uses the style of the character at the **start** - 1 position or, if that character does not have style set, the style of the character at the **start** position.| 224 225**Error codes** 226 227For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). 228 229| ID| Error Message| 230| ------- | -------- | 231| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | 232 233### removeString 234 235Removes the string in the specified range of this styled string. 236 237This API equally works when the styled string contains an image. 238 239removeString(start: number , length: number): void 240 241**Atomic service API**: This API can be used in atomic services since API version 12. 242 243**System capability**: SystemCapability.ArkUI.ArkUI.Full 244 245**Parameters** 246 247| Name | Type | Mandatory| Description | 248| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 249| start | number | Yes | Subscript of the target range.| 250| length | number | Yes | Length of the target range.| 251 252**Error codes** 253 254For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). 255 256| ID| Error Message| 257| ------- | -------- | 258| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | 259 260### replaceStyle 261 262Replaces the style in the specified range of this styled string. 263 264replaceStyle(spanStyle: SpanStyle): void 265 266**Atomic service API**: This API can be used in atomic services since API version 12. 267 268**System capability**: SystemCapability.ArkUI.ArkUI.Full 269 270**Parameters** 271 272| Name | Type | Mandatory| Description | 273| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 274| spanStyle | [SpanStyle](#spanstyle) | Yes | Style object.<br>**NOTE**<br>By default, the original style is removed and replaced with the new style.<br>If **styledKey** of **SpanStyle** is **IMAGE**, this API takes effect only when an image with the length of 1 is at the **start** position.| 275 276**Error codes** 277 278For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). 279 280| ID| Error Message| 281| ------- | -------- | 282| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | 283 284### setStyle 285 286Sets a new style for the specified range of this styled string. 287 288setStyle(spanStyle: SpanStyle): void 289 290**Atomic service API**: This API can be used in atomic services since API version 12. 291 292**System capability**: SystemCapability.ArkUI.ArkUI.Full 293 294**Parameters** 295 296| Name | Type | Mandatory| Description | 297| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 298| spanStyle | [SpanStyle](#spanstyle) | Yes | Style object.<br>**NOTE**<br>By default, the new style is applied without removing the original style. If the style already exists, it is updated.<br>If **styledKey** of **SpanStyle** is **IMAGE**, this API takes effect only when an image with the length of 1 is at the **start** position.| 299 300### removeStyle 301 302Removes the style for the specified range of this styled string. 303 304After a style is removed, the value set for the corresponding style attribute in the [Text](./ts-basic-components-text.md) component is used. If the value is not set, the default value is used. 305 306This API equally works when the styled string contains an image. 307 308removeStyle(start: number , length: number , styledKey: StyledStringKey): void 309 310**Atomic service API**: This API can be used in atomic services since API version 12. 311 312**System capability**: SystemCapability.ArkUI.ArkUI.Full 313 314**Parameters** 315 316| Name | Type | Mandatory| Description | 317| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 318| start | number | Yes | Subscript that corresponds to the start position of the target range.| 319| length | number | Yes | Length of the target range.| 320| styledKey | [StyledStringKey](#styledstringkey12) | Yes | Styled key.| 321 322**Error codes** 323 324For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). 325 326| ID| Error Message| 327| ------- | -------- | 328| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | 329 330### removeStyles 331 332Removes all styles for the specified range of this styled string. 333 334After a style is removed, the value set for the corresponding style attribute in the [Text](./ts-basic-components-text.md) component is used. If the value is not set, the default value is used. 335 336This API equally works when the styled string contains an image. 337 338removeStyles(start: number , length: number): void 339 340**Atomic service API**: This API can be used in atomic services since API version 12. 341 342**System capability**: SystemCapability.ArkUI.ArkUI.Full 343 344**Parameters** 345 346| Name | Type | Mandatory| Description | 347| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 348| start | number | Yes | Subscript that corresponds to the start position of the target range.| 349| length | number | Yes | Length of the target range.| 350 351**Error codes** 352 353For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). 354 355| ID| Error Message| 356| ------- | -------- | 357| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | 358 359### clearStyles 360 361Removes all styles of this styled string. 362 363After a style is removed, the value set for the corresponding style attribute in the [Text](./ts-basic-components-text.md) component is used. If the value is not set, the default value is used. 364 365clearStyles(): void 366 367**Atomic service API**: This API can be used in atomic services since API version 12. 368 369**System capability**: SystemCapability.ArkUI.ArkUI.Full 370 371### replaceStyledString 372 373Replaces the styled string in the specified range. 374 375replaceStyledString(start: number , length: number , other: StyledString): void 376 377**Atomic service API**: This API can be used in atomic services since API version 12. 378 379**System capability**: SystemCapability.ArkUI.ArkUI.Full 380 381**Parameters** 382 383| Name | Type | Mandatory| Description | 384| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 385| start | number | Yes | Subscript that corresponds to the start position of the target range.| 386| length | number | Yes | Length of the target range.| 387| other | [StyledString](#styledstring) | Yes | New styled string.| 388 389**Error codes** 390 391For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). 392 393| ID| Error Message| 394| ------- | -------- | 395| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | 396 397### insertStyledString 398 399Inserts a new styled string at the specified position. 400 401insertStyledString(start: number , other: StyledString): void 402 403**Atomic service API**: This API can be used in atomic services since API version 12. 404 405**System capability**: SystemCapability.ArkUI.ArkUI.Full 406 407**Parameters** 408 409| Name | Type | Mandatory| Description | 410| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 411| start | number | Yes | Subscript of the position to insert the styled string.| 412| other | [StyledString](#styledstring) | Yes | New styled string.| 413 414**Error codes** 415 416For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). 417 418| ID| Error Message| 419| ------- | -------- | 420| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | 421 422### appendStyledString 423 424Appends a styled string. 425 426appendStyledString(other: StyledString): void 427 428**Atomic service API**: This API can be used in atomic services since API version 12. 429 430**System capability**: SystemCapability.ArkUI.ArkUI.Full 431 432**Parameters** 433 434| Name | Type | Mandatory| Description | 435| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 436| other | [StyledString](#styledstring) | Yes | New styled string.| 437 438## StyleOptions 439 440**Atomic service API**: This API can be used in atomic services since API version 12. 441 442| Name | Type | Mandatory| Description | 443| ------- | --------------------------------- | ---- | --------------------------------- | 444| start | number | No | Start position of the styled string style.| 445| length | number | No | Length of the styled string style.| 446| styledKey | [StyledStringKey](#styledstringkey12) | Yes | Style key.| 447| styledValue | [StyledStringValue](ts-types.md#styledstringvalue12) | Yes | Style object.| 448 449## SpanStyle 450 451**Atomic service API**: This API can be used in atomic services since API version 12. 452 453| Name | Type | Mandatory| Description | 454| ------- | --------------------------------- | ---- | --------------------------------- | 455| start | number | Yes | Start position of the styled string style.| 456| length | number | Yes | Length of the styled string style.| 457| styledKey | [StyledStringKey](#styledstringkey12) | Yes | Style key.| 458| styledValue | [StyledStringValue](ts-types.md#styledstringvalue12) | Yes | Style object.| 459 460## TextStyle 461 462Describes the text font style. 463 464**System capability**: SystemCapability.ArkUI.ArkUI.Full 465 466### Attributes 467 468**Atomic service API**: This API can be used in atomic services since API version 12. 469 470**System capability**: SystemCapability.ArkUI.ArkUI.Full 471 472| Name | Type | Read Only | Mandatory | Description | 473| ------------ |---------------------| ---- | ---- | ------ | 474| fontColor | [ResourceColor](ts-types.md#resourcecolor) | Yes | No | Font color of the styled string.| 475| fontFamily | string | Yes | No | Font family of the styled string.| 476| fontSize | number | Yes | No | Font size of the styled string.<br>Unit: fp| 477| fontWeight | number | Yes | No | Font weight of the styled string.| 478| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Yes | No | Font style of the styled string.| 479 480### constructor 481 482constructor(value?: TextStyleInterface) 483 484**Atomic service API**: This API can be used in atomic services since API version 12. 485 486**System capability**: SystemCapability.ArkUI.ArkUI.Full 487 488**Parameters** 489 490| Name | Type | Mandatory| Description | 491| ------- | --------------------------------- | ---- | --------------------------------- | 492| value | [TextStyleInterface](#textstyleinterface) | No | Font style options.| 493 494## TextStyleInterface 495 496**Atomic service API**: This API can be used in atomic services since API version 12. 497 498| Name | Type | Mandatory| Description | 499| ------- | --------------------------------- | ---- | --------------------------------- | 500| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color.| 501| fontFamily | [ResourceStr](ts-types.md#resourcestr) | No | Font family.| 502| fontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No | Font size. If **unit** of **LengthMetrics** is percent, the setting does not take effect, and 16 fp is used.| 503| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | No | Font weight.| 504| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | No | Font style.| 505 506## GestureStyle 507 508Describes the event gesture style. 509 510**System capability**: SystemCapability.ArkUI.ArkUI.Full 511 512### constructor 513 514constructor(value?: GestureStyleInterface) 515 516**Atomic service API**: This API can be used in atomic services since API version 12. 517 518**System capability**: SystemCapability.ArkUI.ArkUI.Full 519 520**Parameters** 521 522| Name | Type | Mandatory| Description | 523| ------- | --------------------------------- | ---- | --------------------------------- | 524| value | [GestureStyleInterface](#gesturestyleinterface) | No | Event options.| 525 526## GestureStyleInterface 527 528**Atomic service API**: This API can be used in atomic services since API version 12. 529 530| Name | Type | Mandatory| Description | 531| ------- | --------------------------------- | ---- | --------------------------------- | 532| onClick | CallBack\<[ClickEvent](ts-universal-events-click.md#clickevent)> | No | Callback for click events.| 533| onLongPress | CallBack\<[GestureEvent](./ts-gesture-settings.md#gestureevent)> | No | Callback for long press events.| 534 535## DecorationStyle 536 537Describes the text decorative line style. 538 539**System capability**: SystemCapability.ArkUI.ArkUI.Full 540 541### Attributes 542 543**Atomic service API**: This API can be used in atomic services since API version 12. 544 545**System capability**: SystemCapability.ArkUI.ArkUI.Full 546 547| Name | Type | Read Only | Mandatory | Description | 548| ------------ |---------------------| ---- | ---- | ------ | 549| type | [TextDecorationType](ts-appendix-enums.md#textdecorationtype) | Yes | Yes | Type of the text decorative line.| 550| color | [ResourceColor](ts-types.md#resourcecolor) | Yes | No | Color of the text decorative line.| 551| style | [TextDecorationStyle](ts-appendix-enums.md#textdecorationstyle12) | Yes | No | Style of the text decorative line.| 552 553### constructor 554 555constructor(value: DecorationStyleInterface) 556 557**Atomic service API**: This API can be used in atomic services since API version 12. 558 559**System capability**: SystemCapability.ArkUI.ArkUI.Full 560 561**Parameters** 562 563| Name | Type | Mandatory| Description | 564| ------- | --------------------------------- | ---- | --------------------------------- | 565| value | [DecorationStyleInterface](#decorationstyleinterface) | Yes | Text decorative line options.| 566 567## DecorationStyleInterface 568 569| Name | Type | Mandatory| Description | 570| ------- | --------------------------------- | ---- | --------------------------------- | 571| type | [TextDecorationType](ts-appendix-enums.md#textdecorationtype) | Yes | Type of the text decorative line.| 572| color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the text decorative line.| 573| style | [TextDecorationStyle](ts-appendix-enums.md#textdecorationstyle12) | No | Style of the text decorative line.| 574 575## DecorationStyleResult 576 577Provides the text decorative line information returned by the backend. 578 579**System capability**: SystemCapability.ArkUI.ArkUI.Full 580 581**Parameters** 582 583| Name | Type | Mandatory| Description | 584| ------- | --------------------------------- | ---- | --------------------------------- | 585| type | [TextDecorationType](ts-appendix-enums.md#textdecorationtype) | Yes | Type of the text decorative line.| 586| color | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the text decorative line.| 587| style | [TextDecorationStyle](ts-appendix-enums.md#textdecorationstyle12) | No | Style of the text decorative line.| 588 589## BaselineOffsetStyle 590 591Describes the text baseline offset style. 592 593**System capability**: SystemCapability.ArkUI.ArkUI.Full 594 595### Attributes 596 597**Atomic service API**: This API can be used in atomic services since API version 12. 598 599**System capability**: SystemCapability.ArkUI.ArkUI.Full 600 601| Name | Type | Read Only | Mandatory | Description | 602| ------------ |---------------------| ---- | ---- | ------ | 603| baselineOffset | number | Yes | Yes | Text baseline offset.<br>Unit: vp| 604 605### constructor 606 607constructor(value: LengthMetrics) 608 609**Atomic service API**: This API can be used in atomic services since API version 12. 610 611**System capability**: SystemCapability.ArkUI.ArkUI.Full 612 613**Parameters** 614 615| Name | Type | Mandatory| Description | 616| ------- | --------------------------------- | ---- | --------------------------------- | 617| value | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Text baseline offset options. This API does not work if **unit** of **LengthMetrics** is percent.| 618 619## LetterSpacingStyle 620 621Describes the letter spacing style. 622 623**System capability**: SystemCapability.ArkUI.ArkUI.Full 624 625### Attributes 626 627**Atomic service API**: This API can be used in atomic services since API version 12. 628 629**System capability**: SystemCapability.ArkUI.ArkUI.Full 630 631| Name | Type | Read Only | Mandatory | Description | 632| ------------ |---------------------| ---- | ---- | ------ | 633| letterSpacing | number | Yes | Yes | Letter spacing.<br>Unit: vp| 634 635### constructor 636 637constructor(value: LengthMetrics) 638 639**Atomic service API**: This API can be used in atomic services since API version 12. 640 641**System capability**: SystemCapability.ArkUI.ArkUI.Full 642 643**Parameters** 644 645| Name | Type | Mandatory| Description | 646| ------- | --------------------------------- | ---- | --------------------------------- | 647| value | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Letter spacing options. This API does not work if **unit** of **LengthMetrics** is percent.| 648 649## LineHeightStyle 650 651Describes the text line height style. 652 653**System capability**: SystemCapability.ArkUI.ArkUI.Full 654 655### Attributes 656 657**Atomic service API**: This API can be used in atomic services since API version 12. 658 659**System capability**: SystemCapability.ArkUI.ArkUI.Full 660 661| Name | Type | Read Only | Mandatory | Description | 662| ------------ |---------------------| ---- | ---- | ------ | 663| lineHeight | number | Yes | Yes | Text line height of the styled string.<br>Unit: vp| 664 665### constructor 666 667constructor(lineHeight: LengthMetrics) 668 669**Atomic service API**: This API can be used in atomic services since API version 12. 670 671**System capability**: SystemCapability.ArkUI.ArkUI.Full 672 673**Parameters** 674 675| Name | Type | Mandatory| Description | 676| ------- | --------------------------------- | ---- | --------------------------------- | 677| lineHeight | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Text line height options. If **value** of **LengthMetrics** is less than or equal to 0, the text line height is unlimited and automatically adapts to the font size.| 678 679## TextShadowStyle 680 681Describes the text shadow style. 682 683**System capability**: SystemCapability.ArkUI.ArkUI.Full 684 685### Attributes 686 687**Atomic service API**: This API can be used in atomic services since API version 12. 688 689**System capability**: SystemCapability.ArkUI.ArkUI.Full 690 691| Name | Type | Read Only | Mandatory | Description | 692| ------------ |---------------------| ---- | ---- | ------ | 693| textShadow | Array\<[ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions)> | Yes | Yes | Text shadow of the styled string.| 694 695### constructor 696 697constructor(value: ShadowOptions | Array\<ShadowOptions>) 698 699**Atomic service API**: This API can be used in atomic services since API version 12. 700 701**System capability**: SystemCapability.ArkUI.ArkUI.Full 702 703**Parameters** 704 705| Name | Type | Mandatory| Description | 706| ------- | --------------------------------- | ---- | --------------------------------- | 707| value | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) \| Array\<[ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions)> | Yes | Text shadow options.| 708 709## ImageAttachment 710 711Describes the image attachment. 712 713**System capability**: SystemCapability.ArkUI.ArkUI.Full 714 715### Attributes 716 717**Atomic service API**: This API can be used in atomic services since API version 12. 718 719**System capability**: SystemCapability.ArkUI.ArkUI.Full 720 721| Name | Type | Read Only | Mandatory | Description | 722| ------------ |---------------------| ---- | ---- | ------ | 723| value | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | Yes | Image data source of the styled string.| 724| size | [SizeOptions](ts-types.md#sizeoptions) | Yes | No | Image size of the styled string.| 725| verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | Yes | No | Image alignment mode of the styled string.| 726| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Yes | No | Image scale type of the styled string.| 727| layoutStyle | [ImageAttachmentLayoutStyle](#imageattachmentlayoutstyle) | Yes | No | Image layout of the styled string.| 728 729### constructor 730 731constructor(value: ImageAttachmentInterface) 732 733**Atomic service API**: This API can be used in atomic services since API version 12. 734 735**System capability**: SystemCapability.ArkUI.ArkUI.Full 736 737**Parameters** 738 739| Name | Type | Mandatory| Description | 740| ------- | --------------------------------- | ---- | --------------------------------- | 741| value | [ImageAttachmentInterface](#imageattachmentinterface) | Yes | Image attachment options.| 742 743## ImageAttachmentInterface 744 745**Atomic service API**: This API can be used in atomic services since API version 12. 746 747| Name | Type | Mandatory| Description | 748| ------- | --------------------------------- | ---- | --------------------------------- | 749| value | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | Image data source.| 750| size | [SizeOptions](ts-types.md#sizeoptions) | No | Image size.| 751| verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | No | Alignment mode of the image with the text.| 752| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | No | Image scale type.| 753| layoutStyle | [ImageAttachmentLayoutStyle](#imageattachmentlayoutstyle) | No | Image layout.| 754 755## ImageAttachmentLayoutStyle 756 757**Atomic service API**: This API can be used in atomic services since API version 12. 758 759| Name | Type | Mandatory| Description | 760| ------- | --------------------------------- | ---- | --------------------------------- | 761| margin | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [Margin](ts-types.md#margin) | No | Image margin.| 762| padding | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [Padding](ts-types.md#padding) | No | Image padding.| 763| borderRadius | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [BorderRadiuses](ts-types.md#borderradiuses9) | No | Radius of the image border corners.| 764 765## CustomSpan 766 767Describes the custom span. Only the base class is provided. You need to define the specific implementation. 768 769The drag preview of a custom span is blank. 770 771**System capability**: SystemCapability.ArkUI.ArkUI.Full 772 773### onMeasure 774 775Called to obtain the size of a custom span. 776 777abstract onMeasure(measureInfo: CustomSpanMeasureInfo): CustomSpanMetrics 778 779**Atomic service API**: This API can be used in atomic services since API version 12. 780 781**System capability**: SystemCapability.ArkUI.ArkUI.Full 782 783**Parameters** 784 785| Name | Type | Mandatory| Description | 786| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 787| measureInfo | [CustomSpanMeasureInfo](#customspanmeasureinfo) | Yes | Font size of the text.| 788 789**Return value** 790 791| Type | Description | 792| ------- | --------------------------------- | 793| [CustomSpanMetrics](#customspanmetrics) | Size of the custom span.<br>**NOTE**<br>The final height of the custom span is subject to the line height of the **Text** component. If no value is specified for **height**, the custom span takes the **fontSize** value of the **Text** component as its height. If the value specified is greater than the height of other child components on the same line, the custom span takes the line height of the **Text** component as its height.| 794 795### onDraw 796 797Called to draw a custom span. 798 799abstract onDraw(context: DrawContext, drawInfo: CustomSpanDrawInfo): void 800 801**Atomic service API**: This API can be used in atomic services since API version 12. 802 803**System capability**: SystemCapability.ArkUI.ArkUI.Full 804 805**Parameters** 806 807| Name | Type | Mandatory| Description | 808| ------- | --------------------------------- | ---- | ------------------------------------------------------------ | 809| context | [DrawContext](../js-apis-arkui-graphics.md#drawcontext) | Yes | Drawing context.<br>**NOTE**<br>The **canvas** method of **DrawContext** obtains the canvas of the **Text** component. As such, the custom span does not extend beyond the area of the **Text** component.| 810| drawInfo | [CustomSpanDrawInfo](#customspandrawinfo) | Yes | Drawing information of the custom span.| 811 812## CustomSpanMeasureInfo 813 814**Atomic service API**: This API can be used in atomic services since API version 12. 815 816| Name | Type | Mandatory| Description | 817| ------- | --------------------------------- | ---- | --------------------------------- | 818| fontSize | number | Yes | Text font size.<br>Unit: fp| 819 820## CustomSpanMetrics 821 822**Atomic service API**: This API can be used in atomic services since API version 12. 823 824| Name | Type | Mandatory| Description | 825| ------- | --------------------------------- | ---- | --------------------------------- | 826| width | number | Yes | Width of the custom span.<br>Unit: vp| 827| height | number | No | Height of the custom span.<br>Unit: vp| 828 829## CustomSpanDrawInfo 830 831**Atomic service API**: This API can be used in atomic services since API version 12. 832 833| Name | Type | Mandatory| Description | 834| ------- | --------------------------------- | ---- | --------------------------------- | 835| x | number | Yes | Offset of the custom span relative to the mounted component.<br>Unit: px| 836| lineTop | number | Yes | Top margin of the custom span relative to the **Text** component.<br>Unit: px| 837| lineBottom | number | Yes | Bottom margin of the custom span relative to the **Text** component.<br>Unit: px| 838| baseline | number | Yes | Baseline offset of the line where the custom span is located.<br>Unit: px| 839 840## ParagraphStyle 841 842Describes the text paragraph style. 843 844Except the first paragraph, all paragraphs are formed using the character escape '\n'. 845 846The style of a paragraph is the one (if any) set for the first element or the paragraph style of the bound component. 847 848**System capability**: SystemCapability.ArkUI.ArkUI.Full 849 850### Attributes 851 852**Atomic service API**: This API can be used in atomic services since API version 12. 853 854**System capability**: SystemCapability.ArkUI.ArkUI.Full 855 856| Name | Type | Read Only | Mandatory | Description | 857| ------------ |---------------------| ---- | ---- | ------ | 858| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Yes | No | Horizontal alignment of the text paragraph.| 859| textIndent | number | Yes | No | First line indent of the text paragraph.| 860| maxLines | number | Yes | No | Maximum number of lines in the text paragraph.| 861| overflow | [TextOverflow](ts-appendix-enums.md#textoverflow) | Yes | No | Display mode when the text is too long in the text paragraph.| 862| wordBreak | [WordBreak](ts-appendix-enums.md#wordbreak11) | Yes | No | Word break rule of the text paragraph.| 863| leadingMargin | number \| [LeadingMarginPlaceholder](ts-basic-components-richeditor.md#leadingmarginplaceholder11) | Yes | No | Indent of the text paragraph.| 864 865> **NOTE** 866> 867> As the **maxLines** and **overflow** attributes of the styled string take effect only in the **Text** component, you are advised to set them in the component. 868 869### constructor 870 871constructor(value?: ParagraphStyleInterface) 872 873**Atomic service API**: This API can be used in atomic services since API version 12. 874 875**System capability**: SystemCapability.ArkUI.ArkUI.Full 876 877**Parameters** 878 879| Name | Type | Mandatory| Description | 880| ------- | --------------------------------- | ---- | --------------------------------- | 881| value | [ParagraphStyleInterface](#paragraphstyleinterface) | No | Paragraph style options.| 882 883## ParagraphStyleInterface 884 885**Atomic service API**: This API can be used in atomic services since API version 12. 886 887| Name | Type | Mandatory| Description | 888| ------- | --------------------------------- | ---- | --------------------------------- | 889| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | No | Horizontal alignment of the text paragraph.| 890| textIndent | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No | First line indent of the text paragraph.| 891| maxLines | number | No | Maximum number of lines in the text paragraph.| 892| overflow | [TextOverflow](ts-appendix-enums.md#textoverflow) | No | Display mode when the text is too long in the text paragraph.<br>This parameter must be used with **maxLines** for the settings to take effect. **TextOverflow.MARQUEE** is not supported.| 893| wordBreak | [WordBreak](ts-appendix-enums.md#wordbreak11) | No | Word break rule of the text paragraph.| 894| leadingMargin | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [LeadingMarginPlaceholder](ts-basic-components-richeditor.md#leadingmarginplaceholder11) | No | Indent of the text paragraph.| 895 896## UserDataSpan 897 898Implements a **UserDataSpan** object for storing and obtaining user data. Only the base class is provided. You need to define the specific implementation. 899 900The extended user data does not affect the display effect. 901 902**Atomic service API**: This API can be used in atomic services since API version 12. 903 904**System capability**: SystemCapability.ArkUI.ArkUI.Full 905 906## StyledStringKey<sup>12+</sup> 907 908**Atomic service API**: This API can be used in atomic services since API version 12. 909 910**System capability**: SystemCapability.ArkUI.ArkUI.Full 911 912| Name | Description | 913| ------ | ----------------------------- | 914| FONT | Font style key, applicable to [TextStyle](./ts-universal-styled-string.md#textstyle).| 915| DECORATION | Text decorative line style key, applicable to [DecorationStyle](./ts-universal-styled-string.md#decorationstyle).| 916| BASELINE_OFFSET | Text baseline offset style key, applicable to [BaselineOffsetStyle](./ts-universal-styled-string.md#baselineoffsetstyle).| 917| LETTER_SPACING | Text letter spacing style key, applicable to [LetterSpacingStyle](./ts-universal-styled-string.md#letterspacingstyle).| 918| LINE_HEIGHT | Text line height style key, applicable to [LineHeightStyle](./ts-universal-styled-string.md#lineheightstyle).| 919| TEXT_SHADOW | Text shadow style key, applicable to [TextShadowStyle](./ts-universal-styled-string.md#textshadowstyle).| 920| GESTURE | Gesture key, applicable to [GestureStyle](./ts-universal-styled-string.md#gesturestyle).| 921| PARAGRAPH_STYLE | Paragraph style key, applicable to [ParagraphStyle](./ts-universal-styled-string.md#paragraphstyle).| 922| IMAGE | Image key, applicable to [ImageAttachment](./ts-universal-styled-string.md#imageattachment).| 923| CUSTOM_SPAN | Custom span key, applicable to [CustomSpan](./ts-universal-styled-string.md#customspan).| 924| USER_DATA | User data span key, applicable to [UserDataSpan](./ts-universal-styled-string.md#userdataspan).| 925 926## Example 927 928### Example 1 929 930This example shows the basic usage of a styled string. 931 932```ts 933// xxx.ets 934@Entry 935@Component 936struct styled_string_demo1 { 937 @State height1: number = 450; 938 @State fontSize1: number = 16; 939 @State fontWeight1: number = 400; 940 @State color1: Color = Color.Blue; 941 scroll: Scroller = new Scroller(); 942 fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue }); 943 fontStyleAttr2: StyledStringValue = new TextStyle({ fontColor: Color.Orange }); 944 // Create a readable and writable styled string object: mutableStyledString1. 945 mutableStyledString1: MutableStyledString = new MutableStyledString ("45-minute workout"); 946 // Create the mutableStyledString2 object whose input parameters contain strings and styles. 947 mutableStyledString2: MutableStyledString = new MutableStyledString("test hello world", [{ 948 start: 0, 949 length: 5, 950 styledKey: StyledStringKey.FONT, 951 styledValue: this.fontStyleAttr1 952 }]); 953 // Create a read-only styled string object: styledString2. 954 styledString2: StyledString = new StyledString("45-minute workout"); 955 spanStyle1: SpanStyle = { 956 start: 0, 957 length: 5, 958 styledKey: StyledStringKey.FONT, 959 styledValue: new TextStyle({ fontColor: Color.Pink }) 960 }; 961 spanStyle2: SpanStyle = { 962 start: 0, 963 length: 2, 964 styledKey: StyledStringKey.FONT, 965 styledValue: new TextStyle({ fontColor: Color.Red }) 966 }; 967 @State string1: string = ''; 968 @State fontColor1: ResourceColor = Color.Red; 969 controller1: TextController = new TextController(); 970 controller2: TextController = new TextController(); 971 controller3: TextController = new TextController(); 972 973 async onPageShow() { 974 this.controller1.setStyledString(this.styledString2) 975 this.controller2.setStyledString(this.mutableStyledString1) 976 this.controller3.setStyledString(this.mutableStyledString2) 977 } 978 979 build() { 980 Column() { 981 Scroll(this.scroll) { 982 Column() { 983 // Display the styled string. 984 Text(undefined, { controller: this.controller1 }) 985 Text(undefined, { controller: this.controller2 }).key('mutableStyledString1') 986 Text(undefined, { controller: this.controller3 }).key('mutableStyledString2') 987 Button('Change string1 Value') 988 .onClick(() => { 989 let result = this.mutableStyledString1.equals(this.styledString2); 990 if (result) { 991 this.string1 = this.mutableStyledString1.getString(); 992 console.info("mutableStyledString1 content:", this.mutableStyledString1.getString()); 993 console.info("mutableStyledString1 length:", this.mutableStyledString1.length); 994 } 995 }) 996 997 // If the styled string conflicts with the span, the span is ignored. The attributes of the Text component take effect if they do not conflict with the styled string. 998 Text(undefined, { controller: this.controller2 }) { 999 Span("span and styledString test") 1000 .fontColor(Color.Yellow) 1001 .decoration({ type: TextDecorationType.LineThrough }) 1002 ImageSpan($r('app.media.icon')) 1003 } 1004 .key('styledString2') 1005 .fontColor(this.fontColor1) 1006 .letterSpacing(10) 1007 .fontSize(32) 1008 .fontWeight(600) 1009 .fontStyle(FontStyle.Italic) 1010 .lineHeight(30) 1011 .textShadow({ radius: 5, color: Color.Blue, offsetX: 5, offsetY: 5 }) 1012 .textCase(TextCase.UpperCase) 1013 .decoration({ type: TextDecorationType.LineThrough, color: Color.Yellow }) 1014 .baselineOffset(2) 1015 .copyOption(CopyOptions.InApp) 1016 .margin({ top: 10 }) 1017 .draggable(true) 1018 1019 // The following is for comparison with the preceding. 1020 Text() { 1021 Span(this.string1) 1022 .fontColor(this.color1) 1023 .decoration({ type: TextDecorationType.LineThrough }) 1024 ImageSpan($r('app.media.icon')) 1025 .width(50).height(50) 1026 } 1027 .letterSpacing(10) 1028 .fontSize(32) 1029 .fontWeight(600) 1030 .fontStyle(FontStyle.Italic) 1031 .lineHeight(30) 1032 .textShadow({ radius: 5, color: Color.Blue, offsetX: 5, offsetY: 5 }) 1033 .textCase(TextCase.UpperCase) 1034 .decoration({ type: TextDecorationType.LineThrough, color: Color.Yellow }) 1035 .baselineOffset(2) 1036 1037 Button('Set Style and Replace Text') 1038 .onClick(() => { 1039 this.mutableStyledString1.replaceStyle({ 1040 start: 2, 1041 length: 2, 1042 styledKey: StyledStringKey.FONT, 1043 styledValue: this.fontStyleAttr1 1044 }) 1045 this.mutableStyledString1.insertString(0, "Blood Pressure: 85 (High)") 1046 this.mutableStyledString1.setStyle({ 1047 start: 2, 1048 length: 2, 1049 styledKey: StyledStringKey.FONT, 1050 styledValue: this.fontStyleAttr2 1051 }) 1052 this.controller2.setStyledString(this.mutableStyledString1) 1053 }) 1054 .margin({ top: 10 }) 1055 1056 Button('Query and Clear Style') 1057 .onClick(() => { 1058 let styles = this.mutableStyledString1.getStyles(0, this.mutableStyledString1.length) 1059 if (styles.length == 2) { 1060 for (let i = 0; i < styles.length; i++) { 1061 console.info('StyledString style object start:' + styles[i].start) 1062 console.info('StyledString style object length:' + styles[i].length) 1063 console.info('StyledString style object key:' + styles[i].styledKey) 1064 if (styles[i].styledKey === 0) { 1065 let fontAttr = styles[i].styledValue as TextStyle; 1066 console.info('StyledString fontColor:' + fontAttr.fontColor) 1067 } 1068 } 1069 } 1070 if (styles[0] !== undefined) { 1071 this.mutableStyledString2.setStyle(styles[0]); 1072 this.controller3.setStyledString(this.mutableStyledString2); 1073 } 1074 this.mutableStyledString1.removeStyles(2, 3); 1075 this.controller2.setStyledString(this.mutableStyledString1); 1076 }) 1077 .margin({ top: 10 }) 1078 }.width('100%') 1079 1080 } 1081 .expandSafeArea([SafeAreaType.KEYBOARD]) 1082 .scrollable(ScrollDirection.Vertical) 1083 .scrollBar(BarState.On) 1084 .scrollBarColor(Color.Gray) 1085 .scrollBarWidth(10) 1086 .edgeEffect(EdgeEffect.None) 1087 } 1088 .width('100%') 1089 } 1090} 1091``` 1092 1093 1094 1095### Example 2 1096 1097This example shows a styled string that supports events. 1098 1099```ts 1100// xxx.ets 1101import { promptAction } from '@kit.ArkUI'; 1102 1103@Entry 1104@Component 1105struct styled_string_demo2 { 1106 scroll: Scroller = new Scroller(); 1107 fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue }); 1108 clickGestureAttr: GestureStyle = new GestureStyle({ 1109 onClick: () => { 1110 promptAction.showToast({ message: 'clickGestureAttr object trigger click event' }) 1111 this.backgroundColor1 = Color.Yellow 1112 } 1113 }) 1114 gestureStyleAttr: GestureStyle = new GestureStyle({ 1115 onClick: () => { 1116 promptAction.showToast({ message: 'gestureStyleAttr object trigger click event' }) 1117 this.backgroundColor1 = Color.Green 1118 }, 1119 onLongPress: () => { 1120 promptAction.showToast({ message: 'gestureStyleAttr object trigger long press event' }) 1121 this.backgroundColor1 = Color.Orange 1122 } 1123 }); 1124 // Create the event object mutableStyledString3. 1125 mutableStyledString3: MutableStyledString = new MutableStyledString("hello world", [{ 1126 start: 0, 1127 length: 5, 1128 styledKey: StyledStringKey.GESTURE, 1129 styledValue: this.clickGestureAttr 1130 }, 1131 { 1132 start: 0, 1133 length: 5, 1134 styledKey: StyledStringKey.FONT, 1135 styledValue: this.fontStyleAttr1 1136 }, 1137 { 1138 start: 6, 1139 length: 5, 1140 styledKey: StyledStringKey.GESTURE, 1141 styledValue: this.gestureStyleAttr 1142 }, 1143 { 1144 start: 6, 1145 length: 5, 1146 styledKey: StyledStringKey.FONT, 1147 styledValue: new TextStyle({ fontColor: Color.Pink }) 1148 }]); 1149 @State fontColor1: ResourceColor = Color.Red; 1150 @State backgroundColor1: ResourceColor | undefined = undefined; 1151 controller3: TextController = new TextController(); 1152 1153 async onPageShow() { 1154 this.controller3.setStyledString(this.mutableStyledString3) 1155 } 1156 1157 build() { 1158 Column() { 1159 Scroll(this.scroll) { 1160 Column({ space: 30 }) { 1161 Button("Change Background Color in Response to Event").backgroundColor(this.backgroundColor1).width('80%') 1162 // Styled string that contains an event 1163 Text(undefined, { controller: this.controller3 }).fontSize(30) 1164 .copyOption(CopyOptions.InApp) 1165 .draggable(true) 1166 .clip(true) 1167 }.width('100%') 1168 } 1169 .expandSafeArea([SafeAreaType.KEYBOARD]) 1170 .scrollable(ScrollDirection.Vertical) 1171 .scrollBar(BarState.On) 1172 .scrollBarColor(Color.Gray) 1173 .scrollBarWidth(10) 1174 .edgeEffect(EdgeEffect.None) 1175 } 1176 .width('100%') 1177 } 1178} 1179``` 1180 1181 1182 1183### Example 3 1184 1185This example shows a styled string that supports text styles. 1186 1187```ts 1188// xxx.ets 1189import { LengthMetrics, LengthUnit } from '@kit.ArkUI' 1190 1191@Entry 1192@Component 1193struct styled_string_demo3 { 1194 fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue }); 1195 fontStyleAttr2: StyledStringValue = new TextStyle({ 1196 fontColor: Color.Orange, 1197 fontSize: LengthMetrics.vp(20), 1198 fontWeight: FontWeight.Bolder, 1199 fontStyle: FontStyle.Italic, 1200 fontFamily: "Arial" 1201 }); 1202 fontStyleAttr3: StyledStringValue = new TextStyle({ 1203 fontColor: Color.Orange, 1204 fontSize: LengthMetrics.vp(20), 1205 fontWeight: FontWeight.Lighter, 1206 fontStyle: FontStyle.Italic, 1207 fontFamily: "Arial" 1208 }); 1209 // Create a styled string object with multiple text styles: mutableStyledString1. 1210 mutableStyledString1: MutableStyledString = new MutableStyledString("45-minute workout", [{ 1211 start: 0, 1212 length: 2, 1213 styledKey: StyledStringKey.FONT, 1214 styledValue: this.fontStyleAttr3 1215 }, { 1216 start: 2, 1217 length: 2, 1218 styledKey: StyledStringKey.FONT, 1219 styledValue: this.fontStyleAttr2 1220 } 1221 ]); 1222 // Create a styled string object with multiple styles: mutableStyledString2. 1223 mutableStyledString2: MutableStyledString = new MutableStyledString("test hello world", [{ 1224 start: 0, 1225 length: 5, 1226 styledKey: StyledStringKey.FONT, 1227 styledValue: this.fontStyleAttr1 1228 }, { 1229 start: 0, 1230 length: 5, 1231 styledKey: StyledStringKey.DECORATION, 1232 styledValue: new DecorationStyle({ type: TextDecorationType.LineThrough, color: Color.Blue }) 1233 }, { 1234 start: 0, 1235 length: 5, 1236 styledKey: StyledStringKey.TEXT_SHADOW, 1237 styledValue: new TextShadowStyle({ 1238 radius: 5, 1239 type: ShadowType.COLOR, 1240 color: Color.Yellow, 1241 offsetX: 10, 1242 offsetY: -10 1243 }) 1244 }, { 1245 start: 0, 1246 length: 5, 1247 styledKey: StyledStringKey.BASELINE_OFFSET, 1248 styledValue: new BaselineOffsetStyle(LengthMetrics.px(20)) 1249 }, { 1250 start: 0, 1251 length: 5, 1252 styledKey: StyledStringKey.LETTER_SPACING, 1253 styledValue: new LetterSpacingStyle(new LengthMetrics(10, LengthUnit.VP)) 1254 }, { 1255 start: 6, 1256 length: 5, 1257 styledKey: StyledStringKey.BASELINE_OFFSET, 1258 styledValue: new BaselineOffsetStyle(LengthMetrics.fp(10)) 1259 } 1260 ]); 1261 @State fontColor1: ResourceColor = Color.Red; 1262 controller: TextController = new TextController(); 1263 options: TextOptions = { controller: this.controller }; 1264 controller2: TextController = new TextController(); 1265 spanStyle1: SpanStyle = { 1266 start: 0, 1267 length: 5, 1268 styledKey: StyledStringKey.FONT, 1269 styledValue: new TextStyle({ fontColor: Color.Pink }) 1270 }; 1271 1272 async onPageShow() { 1273 this.controller.setStyledString(this.mutableStyledString1) 1274 this.controller2.setStyledString(this.mutableStyledString2) 1275 } 1276 1277 build() { 1278 Column() { 1279 Column({ space: 10 }) { 1280 // Display the styled string configured with various font styles. If the styled string conflicts with the style settings in the Text component, the style set in the styled string takes effect. 1281 Text(undefined, this.options) 1282 .fontColor(this.fontColor1) 1283 .font({ size: 20, weight: 500, style: FontStyle.Normal }) 1284 // Display the styled string for which the text shadow, text decorative line, letter spacing, and baseline offset are configured. If the styled string conflicts with the style settings in the Text component, the style set in the styled string takes effect. 1285 Text(undefined, { controller: this.controller2 }) 1286 .fontSize(30) 1287 .copyOption(CopyOptions.InApp) 1288 .draggable(true) 1289 .decoration({ type: TextDecorationType.Overline, color: Color.Pink }) 1290 .textShadow({ 1291 radius: 10, 1292 type: ShadowType.COLOR, 1293 color: Color.Green, 1294 offsetX: -10, 1295 offsetY: 10 1296 }) 1297 Button('Query Font Style') 1298 .onClick(() => { 1299 let styles = this.mutableStyledString1.getStyles(0, this.mutableStyledString1.length) 1300 if (styles.length !== 0) { 1301 for (let i = 0; i < styles.length; i++) { 1302 console.info('mutableStyledString1 style object start:' + styles[i].start) 1303 console.info('mutableStyledString1 style object length:' + styles[i].length) 1304 console.info('mutableStyledString1 style object key:' + styles[i].styledKey) 1305 if (styles[i].styledKey === 0) { 1306 let fontAttr = styles[i].styledValue as TextStyle; 1307 console.info('mutableStyledString1 fontColor:' + fontAttr.fontColor) 1308 console.info('mutableStyledString1 fontSize:' + fontAttr.fontSize) 1309 console.info('mutableStyledString1 fontWeight:' + fontAttr.fontWeight) 1310 console.info('mutableStyledString1 fontStyle:' + fontAttr.fontStyle) 1311 console.info('mutableStyledString1 fontStyle:' + fontAttr.fontFamily) 1312 } 1313 } 1314 } 1315 }) 1316 .margin({ top: 10 }) 1317 Button('Query Other Styles') 1318 .onClick(() => { 1319 let styles = this.mutableStyledString2.getStyles(0, this.mutableStyledString2.length) 1320 if (styles.length !== 0) { 1321 for (let i = 0; i < styles.length; i++) { 1322 console.info('mutableStyledString2 style object start:' + styles[i].start) 1323 console.info('mutableStyledString2 style object length:' + styles[i].length) 1324 console.info('mutableStyledString2 style object key:' + styles[i].styledKey) 1325 if (styles[i].styledKey === 1) { 1326 let decoAttr = styles[i].styledValue as DecorationStyle; 1327 console.info('mutableStyledString2 decoration type:' + decoAttr.type) 1328 console.info('mutableStyledString2 decoration color:' + decoAttr.color) 1329 } 1330 if (styles[i].styledKey === 2) { 1331 let baselineAttr = styles[i].styledValue as BaselineOffsetStyle; 1332 console.info('mutableStyledString2 baselineOffset:' + baselineAttr.baselineOffset) 1333 } 1334 if (styles[i].styledKey === 3) { 1335 let letterAttr = styles[i].styledValue as LetterSpacingStyle; 1336 console.info('mutableStyledString2 letterSpacing:' + letterAttr.letterSpacing) 1337 } 1338 if (styles[i].styledKey === 4) { 1339 let textShadowAttr = styles[i].styledValue as TextShadowStyle; 1340 let shadowValues = textShadowAttr.textShadow; 1341 if (shadowValues.length > 0) { 1342 for (let j = 0; j < shadowValues.length; j++) { 1343 console.info('mutableStyledString2 textShadow type:' + shadowValues[j].type); 1344 console.info('mutableStyledString2 textShadow radius:' + shadowValues[j].radius); 1345 console.info('mutableStyledString2 textShadow color:' + shadowValues[j].color); 1346 console.info('mutableStyledString2 textShadow offsetX:' + shadowValues[j].offsetX); 1347 console.info('mutableStyledString2 textShadow offsetY:' + shadowValues[j].offsetY); 1348 } 1349 } 1350 } 1351 } 1352 } 1353 }) 1354 .margin({ top: 10 }) 1355 Button('Update mutableStyledString1 Style') 1356 .onClick(() => { 1357 this.mutableStyledString1.setStyle(this.spanStyle1) 1358 this.controller.setStyledString(this.mutableStyledString1) 1359 }) 1360 .margin({ top: 10 }) 1361 }.width('100%') 1362 } 1363 .width('100%') 1364 } 1365} 1366``` 1367 1368 1369### Example 4 1370 1371This example shows a styled string that contains an image. 1372 1373```ts 1374// xxx.ets 1375import { image } from '@kit.ImageKit' 1376import { LengthMetrics } from '@kit.ArkUI' 1377 1378@Entry 1379@Component 1380struct styled_string_demo4 { 1381 @State message: string = 'Hello World' 1382 imagePixelMap: image.PixelMap | undefined = undefined 1383 @State imagePixelMap3: image.PixelMap | undefined = undefined 1384 mutableStr: MutableStyledString = new MutableStyledString('123'); 1385 controller: TextController = new TextController(); 1386 mutableStr2: MutableStyledString = new MutableStyledString('This is set decoration line style to the mutableStr2', [{ 1387 start: 0, 1388 length: 15, 1389 styledKey: StyledStringKey.DECORATION, 1390 styledValue: new DecorationStyle({ 1391 type: TextDecorationType.Overline, 1392 color: Color.Orange, 1393 style: TextDecorationStyle.DOUBLE 1394 }) 1395 }]) 1396 1397 async aboutToAppear() { 1398 console.info("aboutToAppear initial imagePixelMap") 1399 this.imagePixelMap = await this.getPixmapFromMedia($r('app.media.icon')) 1400 } 1401 1402 private async getPixmapFromMedia(resource: Resource) { 1403 let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({ 1404 bundleName: resource.bundleName, 1405 moduleName: resource.moduleName, 1406 id: resource.id 1407 }) 1408 let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength)) 1409 let createPixelMap: image.PixelMap = await imageSource.createPixelMap({ 1410 desiredPixelFormat: image.PixelMapFormat.RGBA_8888 1411 }) 1412 await imageSource.release() 1413 return createPixelMap 1414 } 1415 1416 build() { 1417 Row() { 1418 Column({ space: 5 }) { 1419 Text(undefined, { controller: this.controller }) 1420 .copyOption(CopyOptions.InApp) 1421 .draggable(true) 1422 .fontSize(30) 1423 1424 Button('Set Image') 1425 .onClick(() => { 1426 if (this.imagePixelMap !== undefined) { 1427 this.mutableStr = new MutableStyledString(new ImageAttachment({ 1428 value: this.imagePixelMap, 1429 size: { width: 50, height: 50 }, 1430 layoutStyle: { borderRadius: LengthMetrics.vp(10) }, 1431 verticalAlign: ImageSpanAlignment.BASELINE, 1432 objectFit: ImageFit.Contain 1433 })) 1434 this.controller.setStyledString(this.mutableStr) 1435 } 1436 }) 1437 1438 Button('Image: Append') 1439 .onClick(() => { 1440 let str = new StyledString('123') 1441 this.mutableStr.appendStyledString(str) 1442 this.controller.setStyledString(this.mutableStr) 1443 }) 1444 1445 Button('Image: Before Insert') 1446 .onClick(() => { 1447 this.mutableStr.insertString(0, '123') 1448 this.controller.setStyledString(this.mutableStr) 1449 }) 1450 1451 Button('Image: After Insert') 1452 .onClick(() => { 1453 this.mutableStr.insertString(1, '123') 1454 this.controller.setStyledString(this.mutableStr) 1455 }) 1456 1457 Button('Image: Replace') 1458 .onClick(() => { 1459 this.mutableStr.replaceString(2, 5, "789") 1460 this.controller.setStyledString(this.mutableStr) 1461 }) 1462 1463 Button('Image: Get') 1464 .onClick(() => { 1465 let imageArray = this.mutableStr.getStyles(0, 1, StyledStringKey.IMAGE) 1466 for (let i = 0; i < imageArray.length; ++i) { 1467 console.info('mutableStr start ' + imageArray[i].start + ' length ' + imageArray[i].length + ' type ' + imageArray[i].styledKey) 1468 if (imageArray[i].styledKey === 300) { 1469 let attachment = imageArray[i].styledValue as ImageAttachment 1470 this.imagePixelMap3 = attachment.value 1471 console.info('mutableStr value ' + JSON.stringify(attachment.value)) 1472 if (attachment.size !== undefined) { 1473 console.info('mutableStr size width ' + attachment.size.width + ' height ' + attachment.size.height) 1474 } 1475 console.info('mutableStr vertical ' + attachment.verticalAlign) 1476 console.info('mutableStr fit ' + attachment.objectFit) 1477 if (attachment.layoutStyle !== undefined) { 1478 let radius = attachment.layoutStyle.borderRadius as BorderRadiuses 1479 console.info('mutableStr radius ' + JSON.stringify(radius)) 1480 } 1481 } 1482 1483 } 1484 }) 1485 1486 Image(this.imagePixelMap3).width(50).height(50) 1487 1488 } 1489 .width('100%') 1490 } 1491 .height('100%') 1492 } 1493} 1494``` 1495 1496 1497 1498### Example 5 1499 1500This example shows a styled string configured with **LineHeightStyle** and **ParagraphStyle**. 1501 1502```ts 1503import { LengthMetrics } from '@kit.ArkUI' 1504const canvasWidth = 1000 1505const canvasHeight = 100 1506class LeadingMarginCreator { 1507 private settings: RenderingContextSettings = new RenderingContextSettings(true) 1508 private offscreenCanvas: OffscreenCanvas = new OffscreenCanvas(canvasWidth, canvasHeight) 1509 private offContext: OffscreenCanvasRenderingContext2D = this.offscreenCanvas.getContext("2d", this.settings) 1510 public static instance: LeadingMarginCreator = new LeadingMarginCreator() 1511 1512 public genSquareMark(fontSize: number): PixelMap { 1513 this.offContext = this.offscreenCanvas.getContext("2d", this.settings) 1514 this.clearCanvas() 1515 const coordinate = fontSize * (1 - 1 / 1.5) / 2 1516 const sideLength = fontSize / 1.5 1517 this.offContext.fillRect(coordinate, coordinate, sideLength, sideLength) 1518 return this.offContext.getPixelMap(0, 0, fontSize, fontSize) 1519 } 1520 1521 private clearCanvas() { 1522 this.offContext.clearRect(0, 0, canvasWidth, canvasHeight) 1523 } 1524} 1525@Entry 1526@Component 1527struct Index { 1528 private leadingMarkCreatorInstance = LeadingMarginCreator.instance 1529 leadingMarginPlaceholder1: LeadingMarginPlaceholder = { 1530 pixelMap: this.leadingMarkCreatorInstance.genSquareMark(24), 1531 size:[15, 15] 1532 } 1533 titleParagraphStyleAttr: ParagraphStyle = new ParagraphStyle({ textAlign: TextAlign.Center }); 1534 // Indent the first line of the first paragraph by 15 vp. 1535 paragraphStyleAttr1: ParagraphStyle = new ParagraphStyle({ textIndent: LengthMetrics.vp(15) }); 1536 // Indent the second paragraph by 15 vp, with a placeholder in the first line. 1537 paragraphStyleAttr2: ParagraphStyle = new ParagraphStyle({ textAlign: TextAlign.Start, leadingMargin: this.leadingMarginPlaceholder1 }); 1538 // Set the maximum number of lines and text overflow mode for the third paragraph, without setting the indent. 1539 paragraphStyleAttr3: ParagraphStyle = new ParagraphStyle({ textAlign: TextAlign.End, maxLines: 1, wordBreak: WordBreak.BREAK_ALL, overflow: TextOverflow.Ellipsis}); 1540 // Line height style object 1541 lineHeightStyle1: LineHeightStyle= new LineHeightStyle(new LengthMetrics(24)); 1542 // Create a paragraph style object paragraphStyledString1. 1543 paragraphStyledString1: StyledString = new StyledString("Paragraph title\nStart of the first paragraph 0123456789 End of the first paragraph\nStart of the second paragraph hello world End of the second paragraph\nThird paragraph ABCDEFGHIJKLMNOPQRSTUVWXYZ", [ 1544 { 1545 start: 0, 1546 length: 4, 1547 styledKey: StyledStringKey.PARAGRAPH_STYLE, 1548 styledValue: this.titleParagraphStyleAttr 1549 }, 1550 { 1551 start: 0, 1552 length: 4, 1553 styledKey: StyledStringKey.LINE_HEIGHT, 1554 styledValue: new LineHeightStyle(new LengthMetrics(50)) 1555 },{ 1556 start: 0, 1557 length: 4, 1558 styledKey: StyledStringKey.FONT, 1559 styledValue: new TextStyle({ fontSize: LengthMetrics.vp(24), fontWeight: FontWeight.Bolder }) 1560 }, 1561 { 1562 start: 5, 1563 length: 3, 1564 styledKey: StyledStringKey.PARAGRAPH_STYLE, 1565 styledValue: this.paragraphStyleAttr1 1566 }, 1567 { 1568 start: 5, 1569 length: 20, 1570 styledKey: StyledStringKey.LINE_HEIGHT, 1571 styledValue: this.lineHeightStyle1 1572 }, 1573 { 1574 start: 32, 1575 length: 5, 1576 styledKey: StyledStringKey.PARAGRAPH_STYLE, 1577 styledValue: this.paragraphStyleAttr2 1578 }, 1579 { 1580 start: 32, 1581 length: 20, 1582 styledKey: StyledStringKey.LINE_HEIGHT, 1583 styledValue: this.lineHeightStyle1 1584 }, 1585 { 1586 start: 60, 1587 length: 5, 1588 styledKey: StyledStringKey.PARAGRAPH_STYLE, 1589 styledValue: this.paragraphStyleAttr3 1590 }, 1591 { 1592 start: 60, 1593 length: 5, 1594 styledKey: StyledStringKey.LINE_HEIGHT, 1595 styledValue: this.lineHeightStyle1 1596 } 1597 ]); 1598 controller: TextController = new TextController(); 1599 async onPageShow() { 1600 this.controller.setStyledString(this.paragraphStyledString1) 1601 } 1602 1603 build() { 1604 Row() { 1605 Column( { space : 5 }) { 1606 Text(undefined, { controller: this.controller }) 1607 .width(240) 1608 .borderWidth(1) 1609 .copyOption(CopyOptions.InApp) 1610 .draggable(true) 1611 1612 // Query the paragraph style. 1613 Text() 1614 .onClick(() => { 1615 let styles = this.paragraphStyledString1.getStyles(0, this.paragraphStyledString1.length) 1616 if (styles.length !== 0) { 1617 for (let i = 0; i < styles.length; i++) { 1618 console.info('paragraphStyledString1 style object start:' + styles[i].start) 1619 console.info('paragraphStyledString1 style object length:' + styles[i].length) 1620 console.info('paragraphStyledString1 style object key:' + styles[i].styledKey) 1621 if (styles[i].styledKey === 200) { 1622 let paraAttr = styles[i].styledValue as ParagraphStyle; 1623 console.info('paragraphStyledString1 textAlign:' + paraAttr.textAlign) 1624 console.info('paragraphStyledString1 textIndent:' + paraAttr.textIndent) 1625 console.info('paragraphStyledString1 maxLines:' + paraAttr.maxLines) 1626 console.info('paragraphStyledString1 wordBreak:' + paraAttr.wordBreak) 1627 console.info('paragraphStyledString1 leadingMargin:' + paraAttr.leadingMargin) 1628 console.info('paragraphStyledString1 overflow:' + paraAttr.overflow) 1629 } 1630 } 1631 } 1632 }) 1633 .margin({ top: 10 }) 1634 } 1635 .width('100%') 1636 } 1637 .height('100%') 1638 } 1639} 1640``` 1641 1642 1643 1644### Example 6 1645 1646This example shows a styled string with a custom span. 1647 1648```ts 1649// xxx.ets 1650import { drawing } from '@kit.ArkGraphics2D' 1651import { image } from '@kit.ImageKit' 1652import { LengthMetrics } from '@kit.ArkUI' 1653 1654class MyCustomSpan extends CustomSpan { 1655 constructor(word: string, width: number, height: number) { 1656 super(); 1657 this.word = word; 1658 this.width = width; 1659 this.height = height; 1660 } 1661 1662 onMeasure(measureInfo: CustomSpanMeasureInfo): CustomSpanMetrics { 1663 return { width: this.width, height: this.height }; 1664 } 1665 1666 onDraw(context: DrawContext, options: CustomSpanDrawInfo) { 1667 let canvas = context.canvas; 1668 1669 const brush = new drawing.Brush(); 1670 brush.setColor({ alpha: 255, red: 0, green: 74, blue: 175 }); 1671 const font = new drawing.Font(); 1672 font.setSize(25); 1673 const textBlob = drawing.TextBlob.makeFromString(this.word, font, drawing.TextEncoding.TEXT_ENCODING_UTF8); 1674 canvas.attachBrush(brush); 1675 canvas.drawRect({ 1676 left: options.x + 10, 1677 right: options.x + vp2px(this.width) - 10, 1678 top: options.lineTop + 10, 1679 bottom: options.lineBottom - 10 1680 }); 1681 1682 brush.setColor({ alpha: 255, red: 23, green: 169, blue: 141 }); 1683 canvas.attachBrush(brush); 1684 canvas.drawTextBlob(textBlob, options.x + 20, options.lineBottom - 15); 1685 canvas.detachBrush(); 1686 } 1687 1688 setWord(word: string) { 1689 this.word = word; 1690 } 1691 1692 width: number = 160; 1693 word: string = "drawing"; 1694 height: number = 10; 1695} 1696 1697@Entry 1698@Component 1699struct styled_string_demo6 { 1700 customSpan2: MyCustomSpan = new MyCustomSpan("change", 130, 10); 1701 customSpan1: MyCustomSpan = new MyCustomSpan("Hello", 80, 10); 1702 customSpan3: MyCustomSpan = new MyCustomSpan("World", 80, 40); 1703 style2: MutableStyledString = new MutableStyledString(this.customSpan2); 1704 style1: MutableStyledString = new MutableStyledString(this.customSpan1); 1705 textStyle: MutableStyledString = new MutableStyledString("123"); 1706 textController: TextController = new TextController(); 1707 imagePixelMap: image.PixelMap | undefined = undefined; 1708 isPageShow: boolean = true; 1709 1710 private async getPixmapFromMedia(resource: Resource) { 1711 let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({ 1712 bundleName: resource.bundleName, 1713 moduleName: resource.moduleName, 1714 id: resource.id 1715 }); 1716 let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength)); 1717 let createPixelMap: image.PixelMap = await imageSource.createPixelMap({ 1718 desiredPixelFormat: image.PixelMapFormat.RGBA_8888, 1719 desiredSize: { width: 50, height: 50 } 1720 }); 1721 await imageSource.release(); 1722 return createPixelMap; 1723 } 1724 1725 async onPageShow() { 1726 if (!this.isPageShow) { 1727 return 1728 } 1729 this.isPageShow = false; 1730 1731 this.style1.appendStyledString(new MutableStyledString("Sample CustomSpan", [ 1732 { 1733 start: 0, 1734 length: 5, 1735 styledKey: StyledStringKey.FONT, 1736 styledValue: new TextStyle({ fontColor: Color.Pink }) 1737 }, { 1738 start: 5, 1739 length: 5, 1740 styledKey: StyledStringKey.FONT, 1741 styledValue: new TextStyle({ fontColor: Color.Orange, fontStyle: FontStyle.Italic }) 1742 }, { 1743 start: 10, 1744 length: 500, 1745 styledKey: StyledStringKey.FONT, 1746 styledValue: new TextStyle({ fontColor: Color.Green, fontWeight: FontWeight.Bold }) 1747 } 1748 ])) 1749 this.style1.appendStyledString(new StyledString(this.customSpan3)) 1750 this.style1.appendStyledString(new StyledString("Custom Span", [{ 1751 start: 0, 1752 length: 5, 1753 styledKey: StyledStringKey.FONT, 1754 styledValue: new TextStyle({ fontColor: Color.Green, fontSize: LengthMetrics.px(50) }) 1755 }])) 1756 this.textController.setStyledString(this.style1) 1757 this.imagePixelMap = await this.getPixmapFromMedia($r('sys.media.ohos_ic_public_voice')).then() 1758 } 1759 1760 build() { 1761 Row() { 1762 Column() { 1763 Text(undefined, { controller: this.textController }) 1764 .copyOption(CopyOptions.InApp) 1765 .fontSize(30) 1766 } 1767 .width('100%') 1768 } 1769 .height('100%') 1770 } 1771} 1772``` 1773 1774 1775 1776### Example 7 1777 1778This example shows the usage of **UserDataSpan**. 1779 1780```ts 1781// xxx.ets 1782class MyUserDateSpan extends UserDataSpan { 1783 constructor(name: string, age: number) { 1784 super() 1785 this.name = name 1786 this.age = age 1787 } 1788 1789 name: string 1790 age: number 1791} 1792 1793@Entry 1794@Component 1795struct styled_string_demo7 { 1796 @State name: string = "world" 1797 @State age: number = 10 1798 controller: TextController = new TextController() 1799 styleString: MutableStyledString = new MutableStyledString("hello world", [{ 1800 start: 0, 1801 length: 11, 1802 styledKey: StyledStringKey.USER_DATA, 1803 styledValue: new MyUserDateSpan("hello", 21) 1804 }]) 1805 1806 onPageShow(): void { 1807 this.controller.setStyledString(this.styleString) 1808 } 1809 1810 build() { 1811 Column() { 1812 Text(undefined, { controller: this.controller }) 1813 Button("get user data").onClick(() => { 1814 let arr = this.styleString.getStyles(0, this.styleString.length) 1815 let userDataSpan = arr[0].styledValue as MyUserDateSpan 1816 this.name = userDataSpan.name 1817 this.age = userDataSpan.age 1818 }) 1819 Text("name:" + this.name + " age: " + this.age) 1820 }.width('100%').height(250).padding({ left: 35, right: 35, top: 35 }) 1821 } 1822} 1823``` 1824 1825 1826