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