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