• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 属性字符串
2
3方便灵活应用文本样式的对象,可通过TextController中的[setStyledString](./ts-basic-components-text.md#setstyledstring12)方法与Text组件绑定,可通过RichEditorStyledStringController中的[setStyledString](ts-basic-components-richeditor.md#setstyledstring12)方法与RichEditor组件绑定。
4
5>  **说明:**
6>
7>  从API Version 12开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
8>
9>  属性字符串目前不支持在worker线程中使用。
10
11## 规则说明
12
13* 当组件样式和属性字符串中的样式冲突时,冲突部分以属性字符串设置的样式为准,未冲突部分则生效组件的样式。
14* 当属性字符串和[Text](./ts-basic-components-text.md)子组件冲突时,属性字符串优先级高,即当Text组件中绑定了属性字符串,忽略Text组件下包含[Span](./ts-basic-components-span.md)等子组件的情况。
15* 不支持@State修饰。
16* 建议将StyledString定义为成员变量,从而避免应用退后台后被销毁。
17
18## StyledString
19
20### constructor
21
22constructor(value: string | ImageAttachment | CustomSpan , styles?: Array\<StyleOptions>)
23
24属性字符串的构造函数。
25
26**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
27
28**系统能力:** SystemCapability.ArkUI.ArkUI.Full
29
30**参数:**
31
32| 参数名 | 类型 | 必填 | 说明 |
33| -------- | -------- | -------- | -------- |
34| value | string \| [ImageAttachment](#imageattachment) \| [CustomSpan](#customspan) | 是 | 属性字符串文本内容。<br/>**说明:** <br/>当value值为ImageAttachment或CustomSpan时,styles参数不生效。  |
35| styles | Array<[StyleOptions](#styleoptions对象说明)> | 否 | 属性字符串初始化选项。<br/>**说明:** <br/>start为异常值时,按默认值0处理。<br/>当start的值合法且length为异常值时,length的值为属性字符串长度与start的值的差值。<br/>StyledStringKey与StyledStringValue不匹配时,不生效。<br/>styledKey参数无默认值。 |
36
37### 属性
38
39**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
40
41**系统能力:** SystemCapability.ArkUI.ArkUI.Full
42
43| 名称  |   类型   |   只读   |   可选   |   说明   |
44| ------ | ------ | ------ | ------ | -------------- |
45| length | number |  是   | 否   | 属性字符串字符的长度。<br/>**说明:** <br/>当属性字符串中包含图片或者CustomSpan时,其返回的长度按1计算。 |
46
47### getString
48
49getString(): string
50
51获取字符串信息。
52
53**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
54
55**系统能力:** SystemCapability.ArkUI.ArkUI.Full
56
57**返回值:**
58
59| 类型              |说明       |
60| ------- | --------------------------------- |
61| string | 属性字符串文本内容。<br/>**说明:** <br/>当属性字符串中包含图片时,其返回的结果用空格表示。 |
62
63### equals
64
65equals(other: StyledString): boolean
66
67判断两个属性字符串是否相等。
68
69**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
70
71**系统能力:** SystemCapability.ArkUI.ArkUI.Full
72
73**参数:**
74
75| 参数名  | 类型                              | 必填 | 说明                                                         |
76| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
77| other | [StyledString](#styledstring) | 是   | StyledString类型的比较对象。 |
78
79**返回值:**
80
81| 类型              |       说明       |
82| ------- | --------------------------------- |
83| boolean | 两个属性字符串是否相等。<br/>true表示相等,false表示不相等。<br/>**说明:** <br/>当属性字符串的文本及样式均一致,视为相等。<br/>不比较GestureStyle,当属性字符串配置了不同事件,文本和其他样式相同时,亦视为相等。<br/>当比较CustomSpan时,比较的是地址,地址相等,视为相等。 |
84
85### subStyledString
86
87subStyledString(start: number , length?: number): StyledString
88
89获取属性字符串的子字符串。
90
91**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
92
93**系统能力:** SystemCapability.ArkUI.ArkUI.Full
94
95**参数:**
96
97| 参数名  | 类型                              | 必填 | 说明                                                         |
98| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
99| start | number | 是   | 子属性字符串开始位置的下标。 |
100| length | number | 否   | 子属性字符串的长度。 |
101
102**返回值:**
103
104| 类型              |       说明       |
105| ------- | --------------------------------- |
106| [StyledString](#styledstring) | 子属性字符串。<br/>**说明:** <br/>当start为合法入参时,length的默认值是被查询属性字符串对象的长度与start的值的差。<br/>当start和length越界或者必填传入undefined时,会抛出异常。|
107
108**错误码**:
109
110以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
111
112| 错误码ID | 错误信息 |
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
120获取指定范围属性字符串的样式集合。
121
122**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
123
124**系统能力:** SystemCapability.ArkUI.ArkUI.Full
125
126**参数:**
127
128| 参数名  | 类型                              | 必填 | 说明                                                         |
129| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
130| start | number | 是   | 指定范围属性字符串的下标。 |
131| length | number | 是   | 指定范围属性字符串的长度。 |
132| styledKey | [StyledStringKey](#styledstringkey枚举说明) | 否   | 指定范围属性字符串样式的枚举值。 |
133
134**返回值:**
135
136| 类型              |       说明       |
137| ------- | --------------------------------- |
138| Array<[SpanStyle](#spanstyle对象说明)> | 各样式对象的数组。<br/>**说明:** <br/>当指定范围属性字符串未设置任何样式,则返回空数组。<br/>当start和length越界或者必填传入undefined时,会抛出异常;<br/>当styledKey传入异常值或undefined时,会抛出异常。<br/>当styledKey为CustomSpan时,返回的是创建CustomSpan时传入的样式对象,即修改该样式对象也会影响实际的显示效果。 |
139
140**错误码**:
141
142以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
143
144| 错误码ID | 错误信息 |
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
152将HTML格式字符串转换成属性字符串,当前支持转换的HTML标签范围:\<p>、\<span>、\<img>。仅支持将这三种标签中的style属性样式转换成对应的属性字符串样式。
153
154**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
155
156**系统能力:** SystemCapability.ArkUI.ArkUI.Full
157
158**参数:**
159
160| 参数名  | 类型                              | 必填 | 说明                                                         |
161| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
162| html | string | 是   | html格式的字符串。 |
163
164**返回值:**
165
166| 类型              |       说明       |
167| ------- | --------------------------------- |
168| [StyledString](#styledstring) | 属性字符串。 |
169
170**错误码**:
171
172以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
173
174| 错误码ID | 错误信息 |
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
182将属性字符串转换成HTML格式字符串。支持转换的属性字符串[StyledStringKey](#styledstringkey枚举说明)包括:StyledStringKey.FONTStyledStringKey.DECORATIONStyledStringKey.LETTER_SPACINGStyledStringKey.TEXT_SHADOWStyledStringKey.LINE_HEIGHTStyledStringKey.IMAGE183
184**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
185
186**系统能力:** SystemCapability.ArkUI.ArkUI.Full
187
188**参数:**
189
190| 参数名  | 类型                              | 必填 | 说明                                                         |
191| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
192| styledString | StyledString | 是   | 属性字符串。 |
193
194**返回值:**
195
196| 类型              |       说明       |
197| ------- | --------------------------------- |
198| string | HTML格式字符串。 |
199
200**错误码**:
201
202以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
203
204| 错误码ID | 错误信息 |
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
210继承于[StyledString](#styledstring)类。
211
212>  **以下接口异常入参处理统一说明:**
213>
214> 当start和length越界或者必填传入undefined时,会抛出异常;
215>
216> 当styledKey和styledValue传入异常值或者两者对应关系不匹配时,会抛出异常。
217>
218
219### replaceString
220
221replaceString(start: number , length: number , other: string): void
222
223替换指定范围的字符串。
224
225**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
226
227**系统能力:** SystemCapability.ArkUI.ArkUI.Full
228
229**参数:**
230
231| 参数名  | 类型                              | 必填 | 说明                                                         |
232| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
233| start | number | 是   | 指定范围的下标。 |
234| length | number | 是   | 指定范围的长度。 |
235| other | string | 是   | 替换的新文本内容。<br/>**说明:** <br/>替换的字符串使用的是start位置字符的样式。 |
236
237**错误码**:
238
239以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
240
241| 错误码ID | 错误信息 |
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
249插入字符串。
250
251**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
252
253**系统能力:** SystemCapability.ArkUI.ArkUI.Full
254
255**参数:**
256
257| 参数名  | 类型                              | 必填 | 说明                                                         |
258| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
259| start | number | 是   | 插入位置的下标。 |
260| other | string | 是   | 插入的新文本内容。<br/>**说明:** <br/>插入的字符串使用的是start-1位置字符的样式。若start-1位置字符未设置样式,则使用start位置字符样式。 |
261
262**错误码**:
263
264以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
265
266| 错误码ID | 错误信息 |
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
274移除指定范围的字符串。
275
276当属性字符串中包含图片时,同样生效。
277
278**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
279
280**系统能力:** SystemCapability.ArkUI.ArkUI.Full
281
282**参数:**
283
284| 参数名  | 类型                              | 必填 | 说明                                                         |
285| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
286| start | number | 是   | 指定范围的下标。 |
287| length | number | 是   | 指定范围的长度。 |
288
289**错误码**:
290
291以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
292
293| 错误码ID | 错误信息 |
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
301替换指定范围内容为指定类型新样式。
302
303**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
304
305**系统能力:** SystemCapability.ArkUI.ArkUI.Full
306
307**参数:**
308
309| 参数名  | 类型                              | 必填 | 说明                                                         |
310| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
311| spanStyle | [SpanStyle](#spanstyle对象说明) | 是   | 样式对象。<br/>**说明:** <br/>默认清空原有样式,替换为新样式。<br/>当SpanStyle的styledKey为IMAGE或CUSTOM_SPAN时,只有当start的位置当前是image或CustomSpan且长度为1,才会生效,其余情况无效果。 |
312
313**错误码**:
314
315以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
316
317| 错误码ID | 错误信息 |
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
325为指定范围内容设置指定类型新样式。
326
327**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
328
329**系统能力:** SystemCapability.ArkUI.ArkUI.Full
330
331**参数:**
332
333| 参数名  | 类型                              | 必填 | 说明                                                         |
334| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
335| spanStyle | [SpanStyle](#spanstyle对象说明) | 是   | 样式对象。<br/>**说明:** <br/>默认不清空原有样式,叠加新样式。若是已有样式,则更新。<br/>当SpanStyle的styledKey为IMAGE或CUSTOM_SPAN时,只有当start的位置当前是image或者CustomSpan且长度为1,才会生效,其余情况无效果。 |
336
337**错误码**:
338
339以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
340
341| 错误码ID | 错误信息 |
342| ------- | -------- |
343| 401      |The parameter check failed.   |
344
345### removeStyle
346
347removeStyle(start: number , length: number , styledKey: StyledStringKey): void
348
349清除指定范围内容的指定类型样式。
350
351被清空样式类型对象属性使用的是对应[Text](./ts-basic-components-text.md)组件属性的设置值,若Text组件未设置值,则使用对应Text组件属性的默认值。
352
353当属性字符串中包含图片时,同样生效。
354
355**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
356
357**系统能力:** SystemCapability.ArkUI.ArkUI.Full
358
359**参数:**
360
361| 参数名  | 类型                              | 必填 | 说明                                                         |
362| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
363| start | number | 是   | 指定范围开始位置的下标。 |
364| length | number | 是   | 指定范围的长度。 |
365| styledKey | [StyledStringKey](#styledstringkey枚举说明) | 是   | 样式类型枚举值。 |
366
367**错误码**:
368
369以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
370
371| 错误码ID | 错误信息 |
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
379清除指定范围内容的所有样式。
380
381被清空样式类型对象属性使用的是对应[Text](./ts-basic-components-text.md)组件属性的设置值,若Text组件未设置值,则使用对应Text组件属性的默认值。
382
383当属性字符串中包含图片时,同样生效。
384
385**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
386
387**系统能力:** SystemCapability.ArkUI.ArkUI.Full
388
389**参数:**
390
391| 参数名  | 类型                              | 必填 | 说明                                                         |
392| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
393| start | number | 是   | 指定范围开始位置的下标。 |
394| length | number | 是   | 指定范围的长度。 |
395
396**错误码**:
397
398以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
399
400| 错误码ID | 错误信息 |
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
408清除属性字符串对象的所有样式。
409
410被清空样式类型对象属性使用的是对应[Text](./ts-basic-components-text.md)组件属性的设置值,若Text组件未设置值,则使用对应Text组件属性的默认值。
411
412**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
413
414**系统能力:** SystemCapability.ArkUI.ArkUI.Full
415
416### replaceStyledString
417
418replaceStyledString(start: number , length: number , other: StyledString): void
419
420替换指定范围为新的属性字符串。
421
422**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
423
424**系统能力:** SystemCapability.ArkUI.ArkUI.Full
425
426**参数:**
427
428| 参数名  | 类型                              | 必填 | 说明                                                         |
429| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
430| start | number | 是   | 指定范围开始位置的下标。 |
431| length | number | 是   | 指定范围的长度。 |
432| other | [StyledString](#styledstring) | 是   | 新的属性字符串对象。 |
433
434**错误码**:
435
436以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
437
438| 错误码ID | 错误信息 |
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
446在指定位置插入新的属性字符串。
447
448**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
449
450**系统能力:** SystemCapability.ArkUI.ArkUI.Full
451
452**参数:**
453
454| 参数名  | 类型                              | 必填 | 说明                                                         |
455| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
456| start | number | 是   | 开始插入位置的下标。 |
457| other | [StyledString](#styledstring) | 是   | 新的属性字符串对象。|
458
459**错误码**:
460
461以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
462
463| 错误码ID | 错误信息 |
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
471在末尾位置追加新的属性字符串。
472
473**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
474
475**系统能力:** SystemCapability.ArkUI.ArkUI.Full
476
477**参数:**
478
479| 参数名  | 类型                              | 必填 | 说明                                                         |
480| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
481| other | [StyledString](#styledstring) | 是   | 新的属性字符串对象。|
482
483
484## StyledStringValue
485
486type StyledStringValue = TextStyle | DecorationStyle | BaselineOffsetStyle | LetterSpacingStyle |
487TextShadowStyle | GestureStyle | ImageAttachment | ParagraphStyle | LineHeightStyle | UrlStyle | CustomSpan | UserDataSpan | BackgroundColorStyle
488
489样式对象类型,用于设置属性字符串的样式。
490
491**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
492
493**系统能力:** SystemCapability.ArkUI.ArkUI.Full
494
495| 类型  | 说明   |
496| ------ | ---------- |
497| [TextStyle](#textstyle) | 文本字体样式。 |
498| [DecorationStyle](#decorationstyle) | 文本装饰线样式。 |
499| [BaselineOffsetStyle](#baselineoffsetstyle) | 文本基线偏移量样式。 |
500| [LetterSpacingStyle](#letterspacingstyle) | 文本字符间距样式。 |
501| [LineHeightStyle](#lineheightstyle) | 文本行高样式。 |
502| [TextShadowStyle](#textshadowstyle) | 文本阴影样式。 |
503| [GestureStyle](#gesturestyle) | 事件手势样式。 |
504| [ParagraphStyle](#paragraphstyle) | 文本段落样式。 |
505| [ImageAttachment](#imageattachment) | 图片样式。 |
506| [CustomSpan](#customspan) | 自定义绘制Span样式。 |
507| [UserDataSpan](#userdataspan) | UserDataSpan样式。 |
508| [UrlStyle](#urlstyle14) | 超链接样式。 |
509| [BackgroundColorStyle](#backgroundcolorstyle14) | 文本背景颜色样式。 |
510
511## StyleOptions对象说明
512
513**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
514
515**系统能力:** SystemCapability.ArkUI.ArkUI.Full
516
517| 名称  | 类型                              | 必填 | 说明   |
518| ------- | --------------------------------- | ---- | --------------------------------- |
519| start | number | 否   | 设置属性字符串样式的开始位置。<br/>当start的值小于0或超出字符串长度时,按0处理。 |
520| length | number | 否   | 设置属性字符串样式的长度。<br/>当length的值小于0或超出字符串长度与start的差值时,按字符串长度与start的差值处理。 |
521| styledKey | [StyledStringKey](#styledstringkey枚举说明) | 是   | 样式类型的枚举值。 |
522| styledValue | [StyledStringValue](#styledstringvalue) | 是   | 样式对象。 |
523
524## SpanStyle对象说明
525
526**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
527
528**系统能力:** SystemCapability.ArkUI.ArkUI.Full
529
530| 名称  | 类型                              | 必填 | 说明   |
531| ------- | --------------------------------- | ---- | --------------------------------- |
532| start | number | 是   | 匹配属性字符串样式的开始位置。 |
533| length | number | 是   | 匹配属性字符串样式的长度。 |
534| styledKey | [StyledStringKey](#styledstringkey枚举说明) | 是   | 样式类型的枚举值。 |
535| styledValue | [StyledStringValue](#styledstringvalue) | 是   | 样式对象。 |
536
537## TextStyle
538
539文本字体样式对象说明。
540
541**系统能力:** SystemCapability.ArkUI.ArkUI.Full
542
543### 属性
544
545**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
546
547**系统能力:** SystemCapability.ArkUI.ArkUI.Full
548
549| 名称           | 类型              | 只读   | 可选   | 说明     |
550| ------------ |---------------------| ---- | ---- | ------ |
551| fontColor  | [ResourceColor](ts-types.md#resourcecolor) |  是  |  是  | 获取属性字符串的文本颜色。 |
552| fontFamily | string   | 是    | 是   | 获取属性字符串的文本字体。<br/>默认返回undefined。 |
553| fontSize   | number   | 是    | 是    | 获取属性字符串的文本字体大小。<br/>单位:fp |
554| fontWeight   | number   | 是    | 是    | 获取属性字符串的文本字体粗细。 |
555| fontStyle   | [FontStyle](ts-appendix-enums.md#fontstyle) | 是    | 是    | 获取属性字符串的文本字体样式。 |
556
557### constructor
558
559constructor(value?: TextStyleInterface)
560
561文本字体样式的构造函数。
562
563**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
564
565**系统能力:** SystemCapability.ArkUI.ArkUI.Full
566
567**参数:**
568
569| 参数名  | 类型                              | 必填 | 说明   |
570| ------- | --------------------------------- | ---- | --------------------------------- |
571| value | [TextStyleInterface](#textstyleinterface对象说明) | 否   | 字体样式设置项。 |
572
573## TextStyleInterface对象说明
574
575**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
576
577**系统能力:** SystemCapability.ArkUI.ArkUI.Full
578
579| 名称  | 类型                              | 必填 | 说明   |
580| ------- | --------------------------------- | ---- | --------------------------------- |
581| fontColor | [ResourceColor](ts-types.md#resourcecolor) | 否   | 字体颜色。 |
582| fontFamily | [ResourceStr](ts-types.md#resourcestr) | 否   | 文本字体。 |
583| fontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 否   | 字体大小。如果LengthMetrics的unit值是percent,当前设置不生效,处理为16fp。<br/>单位:fp |
584| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | 否   | 字体粗细。<br/>number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。 |
585| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | 否   | 字体样式。 |
586
587## GestureStyle
588
589事件手势对象说明。
590
591**系统能力:** SystemCapability.ArkUI.ArkUI.Full
592
593### constructor
594
595constructor(value?: GestureStyleInterface)
596
597事件手势的构造函数。
598
599**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
600
601**系统能力:** SystemCapability.ArkUI.ArkUI.Full
602
603**参数:**
604
605| 参数名  | 类型                              | 必填 | 说明   |
606| ------- | --------------------------------- | ---- | --------------------------------- |
607| value | [GestureStyleInterface](#gesturestyleinterface对象说明) | 否   | 事件设置项。 |
608
609## GestureStyleInterface对象说明
610
611**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
612
613**系统能力:** SystemCapability.ArkUI.ArkUI.Full
614
615| 名称  | 类型                              | 必填 | 说明   |
616| ------- | --------------------------------- | ---- | --------------------------------- |
617| onClick | Callback\<[ClickEvent](ts-universal-events-click.md#clickevent对象说明)> | 否   | 设置点击事件。 |
618| onLongPress | Callback\<[GestureEvent](./ts-gesture-settings.md#gestureevent对象说明)> | 否   | 设置长按事件。 |
619
620## DecorationStyle
621
622文本装饰线样式对象说明。
623
624**系统能力:** SystemCapability.ArkUI.ArkUI.Full
625
626### 属性
627
628**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
629
630**系统能力:** SystemCapability.ArkUI.ArkUI.Full
631
632| 名称           | 类型              | 只读   |可选   | 说明     |
633| ------------ |---------------------| ---- | ---- | ------ |
634| type  | [TextDecorationType](ts-appendix-enums.md#textdecorationtype) |  是  |  否  | 获取属性字符串的文本装饰线类型。 |
635| color | [ResourceColor](ts-types.md#resourcecolor)   | 是    | 是  | 获取属性字符串的文本装饰线颜色。 |
636| style | [TextDecorationStyle](ts-appendix-enums.md#textdecorationstyle12) | 是    |是  | 获取属性字符串的文本装饰线样式。 |
637
638### constructor
639
640constructor(value: DecorationStyleInterface)
641
642文本装饰线样式的构造函数。
643
644**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
645
646**系统能力:** SystemCapability.ArkUI.ArkUI.Full
647
648**参数:**
649
650| 参数名  | 类型                              | 必填 | 说明   |
651| ------- | --------------------------------- | ---- | --------------------------------- |
652| value | [DecorationStyleInterface](#decorationstyleinterface对象说明) | 是   | 文本装饰线设置项。<br/>默认值:<br/>{<br/>&nbsp;type:&nbsp;TextDecorationType.None,<br/>&nbsp;color:&nbsp;Color.Black,<br/>&nbsp;style:&nbsp;TextDecorationStyle.SOLID&nbsp;<br/>} |
653
654## DecorationStyleInterface对象说明
655
656**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
657
658**系统能力:** SystemCapability.ArkUI.ArkUI.Full
659
660| 名称  | 类型                              | 必填 | 说明   |
661| ------- | --------------------------------- | ---- | --------------------------------- |
662| type | [TextDecorationType](ts-appendix-enums.md#textdecorationtype) | 是   | 装饰线类型。 |
663| color | [ResourceColor](ts-types.md#resourcecolor) | 否   | 装饰线颜色。 |
664| style | [TextDecorationStyle](ts-appendix-enums.md#textdecorationstyle12) | 否   | 装饰线样式。 |
665
666## BaselineOffsetStyle
667
668文本基线偏移量对象说明。
669
670**系统能力:** SystemCapability.ArkUI.ArkUI.Full
671
672### 属性
673
674**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
675
676**系统能力:** SystemCapability.ArkUI.ArkUI.Full
677
678| 名称           | 类型              | 只读   | 可选   | 说明     |
679| ------------ |---------------------| ---- | ---- | ------ |
680| baselineOffset  | number |  是  |  否 | 获取属性字符串的文本基线偏移量。<br/>单位:vp |
681
682### constructor
683
684constructor(value: LengthMetrics)
685
686文本基线偏移的构造函数。
687
688**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
689
690**系统能力:** SystemCapability.ArkUI.ArkUI.Full
691
692**参数:**
693
694| 参数名  | 类型                              | 必填 | 说明   |
695| ------- | --------------------------------- | ---- | --------------------------------- |
696| value | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 是   | 文本基线偏移量设置项。如果LengthMetrics的unit值是percent,该设置不生效。 |
697
698## LetterSpacingStyle
699
700文本字符间距对象说明。
701
702**系统能力:** SystemCapability.ArkUI.ArkUI.Full
703
704### 属性
705
706**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
707
708**系统能力:** SystemCapability.ArkUI.ArkUI.Full
709
710| 名称           | 类型              | 只读   | 可选   | 说明     |
711| ------------ |---------------------| ---- | ---- | ------ |
712| letterSpacing  | number |  是  |  否  | 获取属性字符串的文本字符间距。<br/>单位:vp |
713
714### constructor
715
716constructor(value: LengthMetrics)
717
718文本字符间距的构造函数。
719
720**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
721
722**系统能力:** SystemCapability.ArkUI.ArkUI.Full
723
724**参数:**
725
726| 参数名  | 类型                              | 必填 | 说明   |
727| ------- | --------------------------------- | ---- | --------------------------------- |
728| value | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 是   | 文本字符间距设置项。如果LengthMetrics的unit值是percent,该设置不生效。 |
729
730## LineHeightStyle
731
732文本行高对象说明。
733
734**系统能力:** SystemCapability.ArkUI.ArkUI.Full
735
736### 属性
737
738**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
739
740**系统能力:** SystemCapability.ArkUI.ArkUI.Full
741
742| 名称           | 类型              | 只读   | 可选   | 说明     |
743| ------------ |---------------------| ---- | ---- | ------ |
744| lineHeight  | number |  是  |  否  | 获取属性字符串的文本行高。<br/>单位:vp |
745
746### constructor
747
748constructor(lineHeight: LengthMetrics)
749
750文本行高的构造函数。
751
752**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
753
754**系统能力:** SystemCapability.ArkUI.ArkUI.Full
755
756**参数:**
757
758| 参数名  | 类型                              | 必填 | 说明   |
759| ------- | --------------------------------- | ---- | --------------------------------- |
760| lineHeight | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 是   | 文本行高设置项。如果LengthMetrics的value值不大于0时,不限制文本行高,自适应字体大小。 |
761
762## TextShadowStyle
763
764文本阴影对象说明。
765
766**系统能力:** SystemCapability.ArkUI.ArkUI.Full
767
768### 属性
769
770**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
771
772**系统能力:** SystemCapability.ArkUI.ArkUI.Full
773
774| 名称           | 类型              | 只读   | 可选   | 说明     |
775| ------------ |---------------------| ---- | ---- | ------ |
776| textShadow  | Array\<[ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明)> |  是  |  否  | 获取属性字符串的文本阴影。 |
777
778### constructor
779
780constructor(value: ShadowOptions | Array\<ShadowOptions>)
781
782文本阴影对象的构造函数。
783
784ShadowOptions对象中不支持fill字段。
785
786**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
787
788**系统能力:** SystemCapability.ArkUI.ArkUI.Full
789
790**参数:**
791
792| 参数名  | 类型                              | 必填 | 说明   |
793| ------- | --------------------------------- | ---- | --------------------------------- |
794| value | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明) \| Array\<[ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明)>  | 是   | 文本阴影设置项。 |
795
796## ImageAttachment
797
798图片对象说明。
799
800**系统能力:** SystemCapability.ArkUI.ArkUI.Full
801
802### 属性
803
804**系统能力:** SystemCapability.ArkUI.ArkUI.Full
805
806| 名称           | 类型              | 只读   | 可选   | 说明     |
807| ------------ |---------------------| ---- | ---- | ------ |
808| value  | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) |  是  |  否  | 获取属性字符串的图片数据源。**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
809| size  | [SizeOptions](ts-types.md#sizeoptions) |  是  |  是  | 获取属性字符串的图片尺寸。**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。<br/>返回number类型值的单位为`px`。 |
810| verticalAlign  | [ImageSpanAlignment](ts-appendix-enums.md#imagespanalignment10) |  是  |  是  | 获取属性字符串的图片对齐方式。**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
811| objectFit  | [ImageFit](ts-appendix-enums.md#imagefit) |  是  |  是  | 获取属性字符串的图片缩放类型。**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
812| layoutStyle  | [ImageAttachmentLayoutStyle](#imageattachmentlayoutstyle对象说明) |  是  |  是  | 获取属性字符串的图片布局。**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
813| colorFilter<sup>15+</sup>  | [ColorFilterType](#colorfiltertype15) |  是  |  是  | 获取属性字符串的图片颜色滤镜效果。**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 |
814
815### constructor
816
817constructor(value: ImageAttachmentInterface)
818
819图片对象的构造函数。
820
821**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
822
823**系统能力:** SystemCapability.ArkUI.ArkUI.Full
824
825**参数:**
826
827| 参数名  | 类型                              | 必填 | 说明   |
828| ------- | --------------------------------- | ---- | --------------------------------- |
829| value | [ImageAttachmentInterface](#imageattachmentinterface对象说明) | 是   | 图片设置项。 |
830
831### constructor<sup>15+</sup>
832
833constructor(attachment: Optional\<AttachmentType\>)
834
835图片对象的构造函数。与value类型入参构造函数相比,attachment参数增加了对undefined类型和[ResourceStr](ts-types.md#resourcestr)类型图片的支持。
836
837**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
838
839**系统能力:** SystemCapability.ArkUI.ArkUI.Full
840
841**参数:**
842
843| 参数名  | 类型                              | 必填 | 说明   |
844| ------- | --------------------------------- | ---- | --------------------------------- |
845| attachment | Optional<[AttachmentType](#attachmenttype15)> | 是   | PixelMap类型或[ResourceStr](ts-types.md#resourcestr)类型图片设置项。 |
846
847## AttachmentType<sup>15+</sup>
848
849type AttachmentType = ImageAttachmentInterface | ResourceImageAttachmentOptions
850
851图片设置项类型,用于设置属性字符串PixelMap类型或[ResourceStr](ts-types.md#resourcestr)类型图片。
852
853**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
854
855**系统能力:** SystemCapability.ArkUI.ArkUI.Full
856
857| 类型  | 说明   |
858| ------ | ---------- |
859| [ImageAttachmentInterface](#imageattachmentinterface对象说明) | PixelMap类型图片设置项。|
860| [ResourceImageAttachmentOptions](#resourceimageattachmentoptions15) | ResourceStr类型图片设置项。 |
861
862## ColorFilterType<sup>15+</sup>
863
864type ColorFilterType = ColorFilter | DrawingColorFilter
865
866图片颜色滤镜设置项类型。
867
868**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
869
870**系统能力:** SystemCapability.ArkUI.ArkUI.Full
871
872| 类型  | 说明   |
873| ------ | ---------- |
874| [ColorFilter](ts-types.md#colorfilter9) | ColorFilter类型图片颜色滤镜设置项。 |
875| [DrawingColorFilter](../../apis-arkgraphics2d/js-apis-graphics-drawing.md#colorfilter) | DrawingColorFilter类型图片颜色滤镜设置项。 |
876
877## ImageAttachmentInterface对象说明
878
879**系统能力:** SystemCapability.ArkUI.ArkUI.Full
880
881| 名称  | 类型                              | 必填 | 说明   |
882| ------- | --------------------------------- | ---- | --------------------------------- |
883| value | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) |  是  | 设置图片数据源。**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
884| size | [SizeOptions](ts-types.md#sizeoptions) | 否   | 设置图片大小。 **原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。<br/>size的默认值与objectFit的值有关,不同的objectFit的值对应size的默认值不同。比如当objectFit的值为Cover时,图片高度为组件高度减去组件上下的内边距,图片宽度为组件宽度减去组件左右的内边距。 |
885| verticalAlign | [ImageSpanAlignment](ts-appendix-enums.md#imagespanalignment10) | 否   | 设置图片基于文本的对齐方式。**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。<br/>默认值:ImageSpanAlignment.BOTTOM |
886| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 否   | 设置图片的缩放类型。 **原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。<br/>默认值:ImageFit.Cover |
887| layoutStyle | [ImageAttachmentLayoutStyle](#imageattachmentlayoutstyle对象说明) | 否   | 设置图片布局。**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
888| colorFilter<sup>15+</sup>  | [ColorFilterType](#colorfiltertype15) |  否  | 设置属性字符串的图片颜色滤镜效果。**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 |
889
890## ImageAttachmentLayoutStyle对象说明
891
892**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
893
894**系统能力:** SystemCapability.ArkUI.ArkUI.Full
895
896| 名称  | 类型                              | 必填 | 说明   |
897| ------- | --------------------------------- | ---- | --------------------------------- |
898| margin | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [Margin](ts-types.md#margin) | 否   | 设置图片外边距。<br/>默认值:0<br/>单位:vp |
899| padding | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [Padding](ts-types.md#padding) | 否   | 设置图片内边距。<br/>默认值:0<br/>单位:vp |
900| borderRadius | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [BorderRadiuses](ts-types.md#borderradiuses9) | 否   | 设置圆角。<br/>默认值:0<br/>单位:vp |
901
902## ResourceImageAttachmentOptions<sup>15+</sup>
903
904ResourceStr类型图片设置项。
905
906**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
907
908**系统能力:** SystemCapability.ArkUI.ArkUI.Full
909
910| 名称  | 类型                              | 必填 | 说明   |
911| ------- | --------------------------------- | ---- | --------------------------------- |
912| resourceValue | Optional<[ResourceStr](ts-types.md#resourcestr)> |  是  | 设置图片数据源。 |
913| size | [SizeOptions](ts-types.md#sizeoptions) | 否   | 设置图片大小。 |
914| verticalAlign | [ImageSpanAlignment](ts-appendix-enums.md#imagespanalignment10) | 否   | 设置图片基于文本的对齐方式。<br/>默认值:ImageSpanAlignment.BOTTOM |
915| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 否   | 设置图片的缩放类型。<br/>默认值:ImageFit.Cover |
916| layoutStyle | [ImageAttachmentLayoutStyle](#imageattachmentlayoutstyle对象说明) | 否   | 设置图片布局。 |
917| colorFilter  | [ColorFilterType](#colorfiltertype15) |  否  | 设置属性字符串的图片颜色滤镜效果。 |
918| syncLoad  | boolean |  否  | 是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。<br/>默认值:false |
919
920## CustomSpan
921
922自定义绘制Span,仅提供基类,具体实现由开发者定义。
923
924自定义绘制Span拖拽显示的缩略图为空白。
925
926**系统能力:** SystemCapability.ArkUI.ArkUI.Full
927
928### onMeasure
929
930abstract onMeasure(measureInfo: CustomSpanMeasureInfo): CustomSpanMetrics
931
932获取自定义绘制Span的尺寸大小。
933
934**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
935
936**系统能力:** SystemCapability.ArkUI.ArkUI.Full
937
938**参数:**
939
940| 参数名  | 类型                              | 必填 | 说明                                                         |
941| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
942| measureInfo | [CustomSpanMeasureInfo](#customspanmeasureinfo对象说明) | 是   | 文本的字体大小。 |
943
944**返回值:**
945
946| 类型              |       说明       |
947| ------- | --------------------------------- |
948| [CustomSpanMetrics](#customspanmetrics对象说明) | 自定义绘制Span的尺寸信息。<br/>**说明:** <br/>最终的CustomSpan的高度是由当前Text组件的行高所决定的。当height不传值,则默认取Text组件的fontSize的值作为CustomSpan的高度;当height大于当前行的其他子组件的高度时,此时height即为Text组件的行高。 |
949
950### onDraw
951
952abstract onDraw(context: DrawContext, drawInfo: CustomSpanDrawInfo): void
953
954绘制自定义绘制Span。
955
956**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
957
958**系统能力:** SystemCapability.ArkUI.ArkUI.Full
959
960**参数:**
961
962| 参数名  | 类型                              | 必填 | 说明                                                         |
963| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
964| context | [DrawContext](../js-apis-arkui-graphics.md#drawcontext) | 是   | 图形绘制上下文。<br/>**说明:** <br/>DrawContext的canvas方法获取的画布是Text组件的画布,绘制时不会超出Text组件的范围。 |
965| drawInfo | [CustomSpanDrawInfo](#customspandrawinfo对象说明) | 是   | 自定义绘制Span的绘制信息。 |
966
967### invalidate<sup>13+<sup>
968
969invalidate(): void
970
971主动刷新使用CustomSpan的Text组件。
972
973**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
974
975**系统能力:** SystemCapability.ArkUI.ArkUI.Full
976
977## CustomSpanMeasureInfo对象说明
978
979**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
980
981**系统能力:** SystemCapability.ArkUI.ArkUI.Full
982
983| 名称  | 类型                              | 必填 | 说明   |
984| ------- | --------------------------------- | ---- | --------------------------------- |
985| fontSize | number |  是  | 设置文本字体大小。<br/>单位:fp |
986
987## CustomSpanMetrics对象说明
988
989**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
990
991**系统能力:** SystemCapability.ArkUI.ArkUI.Full
992
993| 名称  | 类型                              | 必填 | 说明   |
994| ------- | --------------------------------- | ---- | --------------------------------- |
995| width | number |  是  | 自定义绘制Span的宽。<br/>单位:vp |
996| height | number |  否  | 自定义绘制Span的高。<br/>单位:vp |
997
998## CustomSpanDrawInfo对象说明
999
1000**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1001
1002**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1003
1004| 名称  | 类型                              | 必填 | 说明   |
1005| ------- | --------------------------------- | ---- | --------------------------------- |
1006| x | number |  是  | 自定义绘制Span相对于挂载组件的偏移。<br/>单位:px |
1007| lineTop | number |  是  | 自定义绘制Span相对于Text组件的上边距。<br/>单位:px |
1008| lineBottom | number |  是  | 自定义绘制Span相对于Text组件的下边距。<br/>单位:px |
1009| baseline | number |  是  | 自定义绘制Span的所在行的基线偏移量。<br/>单位:px |
1010
1011## ParagraphStyle
1012
1013文本段落样式对象说明。
1014
1015除首个段落外,后续段落按'\n'划分。
1016
1017每个段落的段落样式按首个占位设置的段落样式生效,未设置时,段落按被绑定组件的段落样式生效。
1018
1019**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1020
1021### 属性
1022
1023**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1024
1025**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1026
1027| 名称           | 类型              | 只读   | 可选   | 说明     |
1028| ------------ |---------------------| ---- | ---- | ------ |
1029| textAlign  | [TextAlign](ts-appendix-enums.md#textalign) |  是  |  是  | 获取属性字符串文本段落在水平方向的对齐方式。 |
1030| textIndent | number   | 是    | 是    | 获取属性字符串文本段落的首行文本缩进。 |
1031| maxLines   | number   | 是    | 是    | 获取属性字符串文本段落的最大行数。 |
1032| overflow   | [TextOverflow](ts-appendix-enums.md#textoverflow)   | 是    | 是   | 获取属性字符串文本段落超长时的显示方式。 |
1033| wordBreak   | [WordBreak](ts-appendix-enums.md#wordbreak11) | 是    | 是    | 获取属性字符串文本段落的断行规则。 |
1034| leadingMargin   | number \| [LeadingMarginPlaceholder](ts-basic-components-richeditor.md#leadingmarginplaceholder11) | 是    | 是   | 获取属性字符串文本段落的缩进。 |
1035
1036>  **说明:**
1037>
1038>  属性字符串的maxLines和overflow仅在Text中生效,建议在组件侧设置。
1039
1040### constructor
1041
1042constructor(value?: ParagraphStyleInterface)
1043
1044文本段落样式的构造函数。
1045
1046**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1047
1048**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1049
1050**参数:**
1051
1052| 参数名  | 类型                              | 必填 | 说明   |
1053| ------- | --------------------------------- | ---- | --------------------------------- |
1054| value | [ParagraphStyleInterface](#paragraphstyleinterface对象说明) | 否   | 段落样式设置项。 |
1055
1056## ParagraphStyleInterface对象说明
1057
1058**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1059
1060**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1061
1062| 名称  | 类型                              | 必填 | 说明   |
1063| ------- | --------------------------------- | ---- | --------------------------------- |
1064| textAlign  | [TextAlign](ts-appendix-enums.md#textalign) |  否  | 设置文本段落在水平方向的对齐方式。 |
1065| textIndent | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12)   | 否    | 设置文本段落的首行文本缩进。 |
1066| maxLines   | number   | 否    | 设置文本段落的最大行数。 |
1067| overflow   | [TextOverflow](ts-appendix-enums.md#textoverflow)   |  否    | 设置文本段落超长时的显示方式。<br />需配合maxLines使用,单独设置不生效。不支持TextOverflow.MARQUEE。 |
1068| wordBreak   | [WordBreak](ts-appendix-enums.md#wordbreak11) | 否    | 设置文本段落的断行规则。 |
1069| leadingMargin   | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [LeadingMarginPlaceholder](ts-basic-components-richeditor.md#leadingmarginplaceholder11) | 否    | 设置文本段落的缩进。 |
1070
1071## UserDataSpan
1072
1073支持存储自定义扩展信息,用于存储和获取用户数据,仅提供基类,具体实现由开发者定义。
1074
1075扩展信息不影响实际显示效果。
1076
1077**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1078
1079**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1080
1081## StyledStringKey枚举说明
1082
1083**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1084
1085| 名称     | 值 | 说明                           |
1086| ------ | --- | ----------------------------- |
1087| FONT | 0 | 字体样式键。[TextStyle](./ts-universal-styled-string.md#textstyle)所属键。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
1088| DECORATION | 1 | 文本装饰线样式键。[DecorationStyle](./ts-universal-styled-string.md#decorationstyle)所属键。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
1089| BASELINE_OFFSET | 2 | 文本基线偏移量样式键。[BaselineOffsetStyle](./ts-universal-styled-string.md#baselineoffsetstyle)所属键。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
1090| LETTER_SPACING | 3 | 文本字符间距样式键。[LetterSpacingStyle](./ts-universal-styled-string.md#letterspacingstyle)所属键。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
1091| TEXT_SHADOW | 4 | 文本阴影样式键。[TextShadowStyle](./ts-universal-styled-string.md#textshadowstyle)所属键。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
1092| LINE_HEIGHT | 5 | 文本行高样式键。[LineHeightStyle](./ts-universal-styled-string.md#lineheightstyle)所属键。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
1093| BACKGROUND_COLOR<sup>14+</sup> | 6 | 文本背景色样式键。[BackgroundColorStyle](./ts-universal-styled-string.md#backgroundcolorstyle14)所属键。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。|
1094| URL<sup>14+</sup> | 7 | 超链接样式键。[UrlStyle](./ts-universal-styled-string.md#urlstyle14)所属键。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。|
1095| GESTURE | 100 | 事件手势键。[GestureStyle](./ts-universal-styled-string.md#gesturestyle)所属键。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
1096| PARAGRAPH_STYLE | 200 | 段落样式键。[ParagraphStyle](./ts-universal-styled-string.md#paragraphstyle)所属键。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
1097| IMAGE | 300 | 图片键。[ImageAttachment](./ts-universal-styled-string.md#imageattachment)所属键。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
1098| CUSTOM_SPAN | 400 | 自定义绘制Span键。[CustomSpan](./ts-universal-styled-string.md#customspan)所属键。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
1099| USER_DATA | 500 | UserDataSpan键。[UserDataSpan](./ts-universal-styled-string.md#userdataspan)所属键。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。|
1100
1101## BackgroundColorStyle<sup>14+</sup>
1102
1103文本背景颜色对象说明。
1104
1105**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1106
1107### 属性
1108
1109**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
1110
1111**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1112
1113| 名称           | 类型              | 只读   | 可选  | 说明     |
1114| ------------ |---------------------| ---- | ---- | ------ |
1115| textBackgroundStyle  |  [TextBackgroundStyle](ts-basic-components-span.md#textbackgroundstyle11对象说明)  |  是  | 否 | 获取属性字符串的文本背景颜色。<br />默认值:<br />{<br /> color: Color.Transparent,<br />  radius: 0<br />} |
1116
1117### constructor<sup>14+</sup>
1118
1119constructor(textBackgroundStyle: TextBackgroundStyle)
1120
1121文本背景颜色的构造函数。
1122
1123**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
1124
1125**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1126
1127**参数:**
1128
1129| 参数名  | 类型                              | 必填 | 说明   |
1130| ------- | --------------------------------- | ---- | --------------------------------- |
1131| textBackgroundStyle |  [TextBackgroundStyle](ts-basic-components-span.md#textbackgroundstyle11对象说明) | 是   | 文本背景色设置项。<br />默认值:<br />{<br />  color: Color.Transparent,<br />  radius: 0<br />} |
1132
1133## UrlStyle<sup>14+</sup>
1134
1135超链接对象说明。
1136
1137默认颜色、字号、字重分别是'#ff0a59f7'、'16fp'、'FontWeight.Regular',若属性字符串设置TextStyle,则TextStyle优先级更高。
1138
1139**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1140
1141### 属性
1142
1143**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
1144
1145**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1146
1147| 名称           | 类型              | 只读   | 可选  | 说明     |
1148| ------------ |---------------------| ---- | ---- | ------ |
1149| url  | string |  是  |  否 | 获取属性字符串的超链接内容。 |
1150
1151### constructor<sup>14+</sup>
1152
1153constructor(url: string)
1154
1155超链接对象的构造函数。
1156
1157**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
1158
1159**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1160
1161**参数:**
1162
1163| 参数名  | 类型                              | 必填 | 说明   |
1164| ------- | --------------------------------- | ---- | --------------------------------- |
1165| url | string | 是   | 超链接设置项。|
1166
1167## 示例
1168
1169### 示例1(属性字符串处理)
1170
1171该示例通过insertString、removeStyles、replaceStyle、getStyles接口实现属性字符串的插入、删除、替换、查看。
1172
1173```ts
1174// xxx.ets
1175@Entry
1176@Component
1177struct styled_string_demo1 {
1178  @State height1: number = 450;
1179  @State fontSize1: number = 16;
1180  @State fontWeight1: number = 400;
1181  @State color1: Color = Color.Blue;
1182  scroll: Scroller = new Scroller();
1183  fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue });
1184  fontStyleAttr2: StyledStringValue = new TextStyle({ fontColor: Color.Orange });
1185  // 创建可读写属性字符串的对象mutableStyledString1
1186  mutableStyledString1: MutableStyledString = new MutableStyledString("运动45分钟");
1187  // 创建构造入参有字符串和样式的对象mutableStyledString2
1188  mutableStyledString2: MutableStyledString = new MutableStyledString("test hello world", [{
1189    start: 0,
1190    length: 5,
1191    styledKey: StyledStringKey.FONT,
1192    styledValue: this.fontStyleAttr1
1193  }]);
1194  // 创建只读属性字符串对象styledString2
1195  styledString2: StyledString = new StyledString("运动45分钟");
1196  spanStyle1: SpanStyle = {
1197    start: 0,
1198    length: 5,
1199    styledKey: StyledStringKey.FONT,
1200    styledValue: new TextStyle({ fontColor: Color.Pink })
1201  };
1202  spanStyle2: SpanStyle = {
1203    start: 0,
1204    length: 2,
1205    styledKey: StyledStringKey.FONT,
1206    styledValue: new TextStyle({ fontColor: Color.Red })
1207  };
1208  @State string1: string = '';
1209  @State fontColor1: ResourceColor = Color.Red;
1210  controller1: TextController = new TextController();
1211  controller2: TextController = new TextController();
1212  controller3: TextController = new TextController();
1213
1214  async onPageShow() {
1215    this.controller1.setStyledString(this.styledString2)
1216    this.controller2.setStyledString(this.mutableStyledString1)
1217    this.controller3.setStyledString(this.mutableStyledString2)
1218  }
1219
1220  build() {
1221    Column() {
1222      Scroll(this.scroll) {
1223        Column() {
1224          // 显示属性字符串
1225          Text(undefined, { controller: this.controller1 })
1226          Text(undefined, { controller: this.controller3 }).key('mutableStyledString2')
1227          Button('修改string1的值')
1228            .onClick(() => {
1229              let result = this.mutableStyledString1.equals(this.styledString2);
1230              if (result) {
1231                this.string1 = this.mutableStyledString1.getString();
1232                console.info("mutableStyledString1 content:", this.mutableStyledString1.getString());
1233                console.info("mutableStyledString1 length:", this.mutableStyledString1.length);
1234              }
1235            })
1236
1237          // 属性字符串与Span冲突时忽略Span,以及样式与Text组件属性未冲突部分生效Text设置的属性
1238          Text(undefined, { controller: this.controller2 }) {
1239            Span("span and styledString test")
1240              .fontColor(Color.Yellow)
1241              .decoration({ type: TextDecorationType.LineThrough })
1242            ImageSpan($r('app.media.icon'))
1243          }
1244          .key('styledString2')
1245          .fontColor(this.fontColor1)
1246          .letterSpacing(10)
1247          .fontSize(32)
1248          .fontWeight(600)
1249          .fontStyle(FontStyle.Italic)
1250          .lineHeight(30)
1251          .textShadow({ radius: 5, color: Color.Blue, offsetX: 5, offsetY: 5 })
1252          .textCase(TextCase.UpperCase)
1253          .decoration({ type: TextDecorationType.LineThrough, color: Color.Yellow })
1254          .baselineOffset(2)
1255          .copyOption(CopyOptions.InApp)
1256          .margin({ top: 10 })
1257          .draggable(true)
1258
1259          // 以上冲突测试对照组
1260          Text() {
1261            Span(this.string1)
1262              .fontColor(this.color1)
1263              .decoration({ type: TextDecorationType.LineThrough })
1264            ImageSpan($r('app.media.icon'))
1265              .width(50).height(50)
1266          }
1267          .letterSpacing(10)
1268          .fontSize(32)
1269          .fontWeight(600)
1270          .fontStyle(FontStyle.Italic)
1271          .lineHeight(30)
1272          .textShadow({ radius: 5, color: Color.Blue, offsetX: 5, offsetY: 5 })
1273          .textCase(TextCase.UpperCase)
1274          .decoration({ type: TextDecorationType.LineThrough, color: Color.Yellow })
1275          .baselineOffset(2)
1276
1277          Button('设置样式及替换文本')
1278            .onClick(() => {
1279              this.mutableStyledString1.replaceStyle({
1280                start: 2,
1281                length: 2,
1282                styledKey: StyledStringKey.FONT,
1283                styledValue: this.fontStyleAttr1
1284              })
1285              this.mutableStyledString1.insertString(0, "压力85偏高,")
1286              this.mutableStyledString1.setStyle({
1287                start: 2,
1288                length: 2,
1289                styledKey: StyledStringKey.FONT,
1290                styledValue: this.fontStyleAttr2
1291              })
1292              this.controller2.setStyledString(this.mutableStyledString1)
1293            })
1294            .margin({ top: 10 })
1295
1296          Button('查询样式及清空样式')
1297            .onClick(() => {
1298              let styles = this.mutableStyledString1.getStyles(0, this.mutableStyledString1.length)
1299              if (styles.length == 2) {
1300                for (let i = 0; i < styles.length; i++) {
1301                  console.info('StyledString style object start:' + styles[i].start)
1302                  console.info('StyledString style object length:' + styles[i].length)
1303                  console.info('StyledString style object key:' + styles[i].styledKey)
1304                  if (styles[i].styledKey === 0) {
1305                    let fontAttr = styles[i].styledValue as TextStyle;
1306                    console.info('StyledString fontColor:' + fontAttr.fontColor)
1307                  }
1308                }
1309              }
1310              if (styles[0] !== undefined) {
1311                this.mutableStyledString2.setStyle(styles[0]);
1312                this.controller3.setStyledString(this.mutableStyledString2);
1313              }
1314              this.mutableStyledString1.removeStyles(2, 3);
1315              this.controller2.setStyledString(this.mutableStyledString1);
1316            })
1317            .margin({ top: 10 })
1318        }.width('100%')
1319
1320      }
1321      .expandSafeArea([SafeAreaType.KEYBOARD])
1322      .scrollable(ScrollDirection.Vertical)
1323      .scrollBar(BarState.On)
1324      .scrollBarColor(Color.Gray)
1325      .scrollBarWidth(10)
1326      .edgeEffect(EdgeEffect.None)
1327    }
1328    .width('100%')
1329  }
1330}
1331```
1332
1333![](figures/styledstring_1.PNG)
1334
1335### 示例2(设置事件)
1336
1337该示例通过styledKey、styledValue接口实现属性字符串绑定事件。
1338
1339```ts
1340// xxx.ets
1341@Entry
1342@Component
1343struct styled_string_demo2 {
1344  scroll: Scroller = new Scroller();
1345  fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue });
1346  private uiContext: UIContext = this.getUIContext();
1347  clickGestureAttr: GestureStyle = new GestureStyle({
1348    onClick: () => {
1349      this.uiContext.getPromptAction().showToast({ message: 'clickGestureAttr object trigger click event' })
1350      this.backgroundColor1 = Color.Yellow
1351    }
1352  })
1353  gestureStyleAttr: GestureStyle = new GestureStyle({
1354    onClick: () => {
1355      this.uiContext.getPromptAction().showToast({ message: 'gestureStyleAttr object trigger click event' })
1356      this.backgroundColor1 = Color.Green
1357    },
1358    onLongPress: () => {
1359      this.uiContext.getPromptAction().showToast({ message: 'gestureStyleAttr object trigger long press event' })
1360      this.backgroundColor1 = Color.Orange
1361    }
1362  });
1363  // 创建事件的对象mutableStyledString3
1364  mutableStyledString3: MutableStyledString = new MutableStyledString("hello world", [{
1365    start: 0,
1366    length: 5,
1367    styledKey: StyledStringKey.GESTURE,
1368    styledValue: this.clickGestureAttr
1369  },
1370    {
1371      start: 0,
1372      length: 5,
1373      styledKey: StyledStringKey.FONT,
1374      styledValue: this.fontStyleAttr1
1375    },
1376    {
1377      start: 6,
1378      length: 5,
1379      styledKey: StyledStringKey.GESTURE,
1380      styledValue: this.gestureStyleAttr
1381    },
1382    {
1383      start: 6,
1384      length: 5,
1385      styledKey: StyledStringKey.FONT,
1386      styledValue: new TextStyle({ fontColor: Color.Pink })
1387    }]);
1388  @State fontColor1: ResourceColor = Color.Red;
1389  @State backgroundColor1: ResourceColor | undefined = undefined;
1390  controller3: TextController = new TextController();
1391
1392  async onPageShow() {
1393    this.controller3.setStyledString(this.mutableStyledString3)
1394  }
1395
1396  build() {
1397    Column() {
1398      Scroll(this.scroll) {
1399        Column({ space: 30 }) {
1400          Button("响应属性字符串事件改变背景色").backgroundColor(this.backgroundColor1).width('80%')
1401          // 包含事件的属性字符串
1402          Text(undefined, { controller: this.controller3 }).fontSize(30)
1403            .copyOption(CopyOptions.InApp)
1404            .draggable(true)
1405            .clip(true)
1406        }.width('100%')
1407      }
1408      .expandSafeArea([SafeAreaType.KEYBOARD])
1409      .scrollable(ScrollDirection.Vertical)
1410      .scrollBar(BarState.On)
1411      .scrollBarColor(Color.Gray)
1412      .scrollBarWidth(10)
1413      .edgeEffect(EdgeEffect.None)
1414    }
1415    .width('100%')
1416  }
1417}
1418```
1419
1420![](figures/styledstring_2.png)
1421
1422### 示例3(设置文本样式)
1423
1424该示例通过getStyles、setStyle接口实现属性字符串查询和设置样式。
1425
1426```ts
1427// xxx.ets
1428import { LengthMetrics, LengthUnit } from '@kit.ArkUI'
1429
1430@Entry
1431@Component
1432struct styled_string_demo3 {
1433  fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue });
1434  fontStyleAttr2: StyledStringValue = new TextStyle({
1435    fontColor: Color.Orange,
1436    fontSize: LengthMetrics.vp(20),
1437    fontWeight: FontWeight.Bolder,
1438    fontStyle: FontStyle.Italic,
1439    fontFamily: "Arial"
1440  });
1441  fontStyleAttr3: StyledStringValue = new TextStyle({
1442    fontColor: Color.Orange,
1443    fontSize: LengthMetrics.vp(20),
1444    fontWeight: FontWeight.Lighter,
1445    fontStyle: FontStyle.Italic,
1446    fontFamily: "Arial"
1447  });
1448  // 创建多重TextStyle样式的对象mutableStyledString1
1449  mutableStyledString1: MutableStyledString = new MutableStyledString("运动45分钟", [{
1450    start: 0,
1451    length: 2,
1452    styledKey: StyledStringKey.FONT,
1453    styledValue: this.fontStyleAttr3
1454  }, {
1455    start: 2,
1456    length: 2,
1457    styledKey: StyledStringKey.FONT,
1458    styledValue: this.fontStyleAttr2
1459  }
1460  ]);
1461  // 创建有多种样式组合对象mutableStyledString2
1462  mutableStyledString2: MutableStyledString = new MutableStyledString("test hello world", [{
1463    start: 0,
1464    length: 5,
1465    styledKey: StyledStringKey.FONT,
1466    styledValue: this.fontStyleAttr1
1467  }, {
1468    start: 0,
1469    length: 5,
1470    styledKey: StyledStringKey.DECORATION,
1471    styledValue: new DecorationStyle({ type: TextDecorationType.LineThrough, color: Color.Blue })
1472  }, {
1473    start: 0,
1474    length: 5,
1475    styledKey: StyledStringKey.TEXT_SHADOW,
1476    styledValue: new TextShadowStyle({
1477      radius: 5,
1478      type: ShadowType.COLOR,
1479      color: Color.Yellow,
1480      offsetX: 10,
1481      offsetY: -10
1482    })
1483  }, {
1484    start: 0,
1485    length: 5,
1486    styledKey: StyledStringKey.BASELINE_OFFSET,
1487    styledValue: new BaselineOffsetStyle(LengthMetrics.px(20))
1488  }, {
1489    start: 0,
1490    length: 5,
1491    styledKey: StyledStringKey.LETTER_SPACING,
1492    styledValue: new LetterSpacingStyle(new LengthMetrics(10, LengthUnit.VP))
1493  }, {
1494    start: 6,
1495    length: 5,
1496    styledKey: StyledStringKey.BASELINE_OFFSET,
1497    styledValue: new BaselineOffsetStyle(LengthMetrics.fp(10))
1498  }
1499  ]);
1500  @State fontColor1: ResourceColor = Color.Red;
1501  controller: TextController = new TextController();
1502  options: TextOptions = { controller: this.controller };
1503  controller2: TextController = new TextController();
1504  spanStyle1: SpanStyle = {
1505    start: 0,
1506    length: 5,
1507    styledKey: StyledStringKey.FONT,
1508    styledValue: new TextStyle({ fontColor: Color.Pink })
1509  };
1510
1511  async onPageShow() {
1512    this.controller.setStyledString(this.mutableStyledString1)
1513    this.controller2.setStyledString(this.mutableStyledString2)
1514  }
1515
1516  build() {
1517    Column() {
1518      Column({ space: 10 }) {
1519        // 显示配了字体各种样式的属性字符串,Text组件亦配置冲突部分生效属性字符串配置,未冲突区间生效Text组件属性设置值
1520        Text(undefined, this.options)
1521          .fontColor(this.fontColor1)
1522          .font({ size: 20, weight: 500, style: FontStyle.Normal })
1523        // 显示配置了文本阴影、划线、字符间距、基线偏移量的属性字符串,Text组件亦配置生效属性字符串配置
1524        Text(undefined, { controller: this.controller2 })
1525          .fontSize(30)
1526          .copyOption(CopyOptions.InApp)
1527          .draggable(true)
1528          .decoration({ type: TextDecorationType.Overline, color: Color.Pink })
1529          .textShadow({
1530            radius: 10,
1531            type: ShadowType.COLOR,
1532            color: Color.Green,
1533            offsetX: -10,
1534            offsetY: 10
1535          })
1536        Button('查询字体样式')
1537          .onClick(() => {
1538            let styles = this.mutableStyledString1.getStyles(0, this.mutableStyledString1.length)
1539            if (styles.length !== 0) {
1540              for (let i = 0; i < styles.length; i++) {
1541                console.info('mutableStyledString1 style object start:' + styles[i].start)
1542                console.info('mutableStyledString1 style object length:' + styles[i].length)
1543                console.info('mutableStyledString1 style object key:' + styles[i].styledKey)
1544                if (styles[i].styledKey === 0) {
1545                  let fontAttr = styles[i].styledValue as TextStyle;
1546                  console.info('mutableStyledString1 fontColor:' + fontAttr.fontColor)
1547                  console.info('mutableStyledString1 fontSize:' + fontAttr.fontSize)
1548                  console.info('mutableStyledString1 fontWeight:' + fontAttr.fontWeight)
1549                  console.info('mutableStyledString1 fontStyle:' + fontAttr.fontStyle)
1550                  console.info('mutableStyledString1 fontStyle:' + fontAttr.fontFamily)
1551                }
1552              }
1553            }
1554          })
1555          .margin({ top: 10 })
1556        Button('查询其他文本样式')
1557          .onClick(() => {
1558            let styles = this.mutableStyledString2.getStyles(0, this.mutableStyledString2.length)
1559            if (styles.length !== 0) {
1560              for (let i = 0; i < styles.length; i++) {
1561                console.info('mutableStyledString2 style object start:' + styles[i].start)
1562                console.info('mutableStyledString2 style object length:' + styles[i].length)
1563                console.info('mutableStyledString2 style object key:' + styles[i].styledKey)
1564                if (styles[i].styledKey === 1) {
1565                  let decoAttr = styles[i].styledValue as DecorationStyle;
1566                  console.info('mutableStyledString2 decoration type:' + decoAttr.type)
1567                  console.info('mutableStyledString2 decoration color:' + decoAttr.color)
1568                }
1569                if (styles[i].styledKey === 2) {
1570                  let baselineAttr = styles[i].styledValue as BaselineOffsetStyle;
1571                  console.info('mutableStyledString2 baselineOffset:' + baselineAttr.baselineOffset)
1572                }
1573                if (styles[i].styledKey === 3) {
1574                  let letterAttr = styles[i].styledValue as LetterSpacingStyle;
1575                  console.info('mutableStyledString2 letterSpacing:' + letterAttr.letterSpacing)
1576                }
1577                if (styles[i].styledKey === 4) {
1578                  let textShadowAttr = styles[i].styledValue as TextShadowStyle;
1579                  let shadowValues = textShadowAttr.textShadow;
1580                  if (shadowValues.length > 0) {
1581                    for (let j = 0; j < shadowValues.length; j++) {
1582                      console.info('mutableStyledString2 textShadow type:' + shadowValues[j].type);
1583                      console.info('mutableStyledString2 textShadow radius:' + shadowValues[j].radius);
1584                      console.info('mutableStyledString2 textShadow color:' + shadowValues[j].color);
1585                      console.info('mutableStyledString2 textShadow offsetX:' + shadowValues[j].offsetX);
1586                      console.info('mutableStyledString2 textShadow offsetY:' + shadowValues[j].offsetY);
1587                    }
1588                  }
1589                }
1590              }
1591            }
1592          })
1593          .margin({ top: 10 })
1594        Button('更新mutableStyledString1样式')
1595          .onClick(() => {
1596            this.mutableStyledString1.setStyle(this.spanStyle1)
1597            this.controller.setStyledString(this.mutableStyledString1)
1598          })
1599          .margin({ top: 10 })
1600      }.width('100%')
1601    }
1602    .width('100%')
1603  }
1604}
1605```
1606![](figures/styledstring_3.png)
1607
1608### 示例4(设置图片)
1609
1610该示例通过ImageAttachment接口实现属性字符串设置图片。
1611
1612```ts
1613// xxx.ets
1614import { image } from '@kit.ImageKit'
1615import { LengthMetrics } from '@kit.ArkUI'
1616
1617@Entry
1618@Component
1619struct styled_string_demo4 {
1620  @State message: string = 'Hello World';
1621  imagePixelMap: image.PixelMap | undefined = undefined
1622  @State imagePixelMap3: image.PixelMap | undefined = undefined
1623  mutableStr: MutableStyledString = new MutableStyledString('123');
1624  controller: TextController = new TextController();
1625  private uiContext: UIContext = this.getUIContext();
1626  mutableStr2: MutableStyledString = new MutableStyledString('This is set decoration line style to the mutableStr2', [{
1627    start: 0,
1628    length: 15,
1629    styledKey: StyledStringKey.DECORATION,
1630    styledValue: new DecorationStyle({
1631      type: TextDecorationType.Overline,
1632      color: Color.Orange,
1633      style: TextDecorationStyle.DOUBLE
1634    })
1635  }])
1636
1637  async aboutToAppear() {
1638    console.info("aboutToAppear initial imagePixelMap")
1639    this.imagePixelMap = await this.getPixmapFromMedia($r('app.media.app_icon'))
1640  }
1641
1642  private async getPixmapFromMedia(resource: Resource) {
1643    let unit8Array = await this.uiContext.getHostContext()?.resourceManager?.getMediaContent({
1644      bundleName: resource.bundleName,
1645      moduleName: resource.moduleName,
1646      id: resource.id
1647    })
1648    let imageSource = image.createImageSource(unit8Array?.buffer.slice(0, unit8Array.buffer.byteLength))
1649    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
1650      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
1651    })
1652    await imageSource.release()
1653    return createPixelMap
1654  }
1655
1656  build() {
1657    Row() {
1658      Column({ space: 5 }) {
1659        Text(undefined, { controller: this.controller })
1660          .copyOption(CopyOptions.InApp)
1661          .draggable(true)
1662          .fontSize(30)
1663        Button('设置图片')
1664          .onClick(() => {
1665            if (this.imagePixelMap !== undefined) {
1666              this.mutableStr = new MutableStyledString(new ImageAttachment({
1667                value: this.imagePixelMap,
1668                size: { width: 50, height: 50 },
1669                layoutStyle: { borderRadius: LengthMetrics.vp(10) },
1670                verticalAlign: ImageSpanAlignment.BASELINE,
1671                objectFit: ImageFit.Contain
1672              }))
1673              this.controller.setStyledString(this.mutableStr)
1674            }
1675          })
1676        Button('设置资源类型图片')
1677          .onClick(() => {
1678            if (this.imagePixelMap !== undefined) {
1679              this.mutableStr = new MutableStyledString(new ImageAttachment({
1680                resourceValue: $r('app.media.sky'), //建议使用自定义的本地图片
1681                size: { width: 50, height: 50 },
1682                layoutStyle: { borderRadius: LengthMetrics.vp(10) },
1683                verticalAlign: ImageSpanAlignment.BASELINE,
1684                objectFit: ImageFit.Contain,
1685                syncLoad: true
1686              }))
1687              this.controller.setStyledString(this.mutableStr)
1688            }
1689          })
1690        Button('Image之Get')
1691          .onClick(() => {
1692            let imageArray = this.mutableStr.getStyles(0, 1, StyledStringKey.IMAGE)
1693            for (let i = 0; i < imageArray.length; ++i) {
1694              console.info('mutableStr start ' + imageArray[i].start + ' length ' + imageArray[i].length + ' type ' +
1695              imageArray[i].styledKey)
1696              if (imageArray[i].styledKey === 300) {
1697                let attachment = imageArray[i].styledValue as ImageAttachment
1698                this.imagePixelMap3 = attachment.value
1699                console.info('mutableStr value ' + JSON.stringify(attachment.value))
1700                if (attachment.size !== undefined) {
1701                  console.info('mutableStr size width ' + attachment.size.width + ' height ' + attachment.size.height)
1702                }
1703                console.info('mutableStr vertical ' + attachment.verticalAlign)
1704                console.info('mutableStr fit ' + attachment.objectFit)
1705                if (attachment.layoutStyle !== undefined) {
1706                  let radius = attachment.layoutStyle.borderRadius as BorderRadiuses
1707                  console.info('mutableStr radius ' + JSON.stringify(radius))
1708                }
1709              }
1710            }
1711          })
1712        Image(this.imagePixelMap3).width(50).height(50)
1713        Button('Image之Append')
1714          .onClick(() => {
1715            let str = new StyledString('123')
1716            this.mutableStr.appendStyledString(str)
1717            this.controller.setStyledString(this.mutableStr)
1718          })
1719        Button('Image之Insert 前')
1720          .onClick(() => {
1721            this.mutableStr.insertString(0, '123')
1722            this.controller.setStyledString(this.mutableStr)
1723          })
1724        Button('Image之Insert 后')
1725          .onClick(() => {
1726            this.mutableStr.insertString(1, '123')
1727            this.controller.setStyledString(this.mutableStr)
1728          })
1729        Button('Image之replace')
1730          .onClick(() => {
1731            this.mutableStr.replaceString(2, 5, "789")
1732            this.controller.setStyledString(this.mutableStr)
1733          })
1734      }
1735      .width('100%')
1736    }
1737    .height('100%')
1738  }
1739}
1740```
1741
1742![](figures/styledstring_4.gif)
1743
1744### 示例5(设置文本行高和段落样式)
1745
1746该示例通过LineHeightStyle、ParagraphStyle接口实现属性字符串设置文本行高和段落样式。
1747
1748```ts
1749import { LengthMetrics } from '@kit.ArkUI'
1750const canvasWidth = 1000
1751const canvasHeight = 100
1752class LeadingMarginCreator {
1753  private settings: RenderingContextSettings = new RenderingContextSettings(true)
1754  private offscreenCanvas: OffscreenCanvas = new OffscreenCanvas(canvasWidth, canvasHeight)
1755  private offContext: OffscreenCanvasRenderingContext2D = this.offscreenCanvas.getContext("2d", this.settings)
1756  public static instance: LeadingMarginCreator = new LeadingMarginCreator()
1757
1758  public genSquareMark(fontSize: number): PixelMap {
1759    this.offContext = this.offscreenCanvas.getContext("2d", this.settings)
1760    this.clearCanvas()
1761    const coordinate = fontSize * (1 - 1 / 1.5) / 2
1762    const sideLength = fontSize / 1.5
1763    this.offContext.fillRect(coordinate, coordinate, sideLength, sideLength)
1764    return this.offContext.getPixelMap(0, 0, fontSize, fontSize)
1765  }
1766
1767  private clearCanvas() {
1768    this.offContext.clearRect(0, 0, canvasWidth, canvasHeight)
1769  }
1770}
1771@Entry
1772@Component
1773struct Index {
1774  private leadingMarkCreatorInstance = LeadingMarginCreator.instance
1775  leadingMarginPlaceholder1: LeadingMarginPlaceholder = {
1776    pixelMap: this.leadingMarkCreatorInstance.genSquareMark(24),
1777    size:[15, 15]
1778  }
1779  titleParagraphStyleAttr: ParagraphStyle = new ParagraphStyle({ textAlign: TextAlign.Center});
1780  //第一段落首行缩进15vp
1781  paragraphStyleAttr1: ParagraphStyle = new ParagraphStyle({ textIndent: LengthMetrics.vp(15) });
1782  //第二段落缩进15vp且首行有placeholder占位显示
1783  paragraphStyleAttr2: ParagraphStyle = new ParagraphStyle({ textAlign: TextAlign.Start, leadingMargin:  this.leadingMarginPlaceholder1 });
1784  //第三段落不设置缩进配置最大行数及超长显示方式
1785  paragraphStyleAttr3: ParagraphStyle = new ParagraphStyle({ textAlign: TextAlign.End, maxLines: 1, wordBreak: WordBreak.BREAK_ALL, overflow: TextOverflow.Ellipsis});
1786  //行高样式对象
1787  lineHeightStyle1: LineHeightStyle= new LineHeightStyle(new LengthMetrics(24));
1788  //创建含段落样式的对象paragraphStyledString1
1789  paragraphStyledString1: StyledString = new StyledString("段落标题\n正文第一段落开始0123456789正文第一段落结束\n正文第二段落开始hello world正文第二段落结束\n正文第三段落ABCDEFGHIJKLMNOPQRSTUVWXYZ。", [
1790    {
1791      start: 0,
1792      length: 4,
1793      styledKey: StyledStringKey.PARAGRAPH_STYLE,
1794      styledValue: this.titleParagraphStyleAttr
1795    },
1796    {
1797      start: 0,
1798      length: 4,
1799      styledKey: StyledStringKey.LINE_HEIGHT,
1800      styledValue: new LineHeightStyle(new LengthMetrics(50))
1801    },{
1802    start: 0,
1803    length: 4,
1804    styledKey: StyledStringKey.FONT,
1805    styledValue: new TextStyle({ fontSize: LengthMetrics.vp(24), fontWeight: FontWeight.Bolder })
1806  },
1807    {
1808      start: 5,
1809      length: 3,
1810      styledKey: StyledStringKey.PARAGRAPH_STYLE,
1811      styledValue: this.paragraphStyleAttr1
1812    },
1813    {
1814      start: 5,
1815      length: 20,
1816      styledKey: StyledStringKey.LINE_HEIGHT,
1817      styledValue: this.lineHeightStyle1
1818    },
1819    {
1820      start: 32,
1821      length: 5,
1822      styledKey: StyledStringKey.PARAGRAPH_STYLE,
1823      styledValue: this.paragraphStyleAttr2
1824    },
1825    {
1826      start: 32,
1827      length: 20,
1828      styledKey: StyledStringKey.LINE_HEIGHT,
1829      styledValue: this.lineHeightStyle1
1830    },
1831    {
1832      start: 60,
1833      length: 5,
1834      styledKey: StyledStringKey.PARAGRAPH_STYLE,
1835      styledValue: this.paragraphStyleAttr3
1836    },
1837    {
1838      start: 60,
1839      length: 5,
1840      styledKey: StyledStringKey.LINE_HEIGHT,
1841      styledValue: this.lineHeightStyle1
1842    }
1843  ]);
1844  controller: TextController = new TextController();
1845  async onPageShow() {
1846    this.controller.setStyledString(this.paragraphStyledString1)
1847  }
1848
1849  build() {
1850    Row() {
1851      Column( { space : 5 }) {
1852        Text(undefined, { controller: this.controller })
1853          .width(240)
1854          .borderWidth(1)
1855          .copyOption(CopyOptions.InApp)
1856          .draggable(true)
1857
1858        //查询段落样式
1859        Text()
1860          .onClick(() => {
1861            let styles = this.paragraphStyledString1.getStyles(0, this.paragraphStyledString1.length)
1862            if (styles.length !== 0) {
1863              for (let i = 0; i < styles.length; i++) {
1864                console.info('paragraphStyledString1 style object start:' + styles[i].start)
1865                console.info('paragraphStyledString1 style object length:' + styles[i].length)
1866                console.info('paragraphStyledString1 style object key:' + styles[i].styledKey)
1867                if (styles[i].styledKey === 200) {
1868                  let paraAttr = styles[i].styledValue as ParagraphStyle;
1869                  console.info('paragraphStyledString1 textAlign:' + paraAttr.textAlign)
1870                  console.info('paragraphStyledString1 textIndent:' + paraAttr.textIndent)
1871                  console.info('paragraphStyledString1 maxLines:' + paraAttr.maxLines)
1872                  console.info('paragraphStyledString1 wordBreak:' + paraAttr.wordBreak)
1873                  console.info('paragraphStyledString1 leadingMargin:' + paraAttr.leadingMargin)
1874                  console.info('paragraphStyledString1 overflow:' + paraAttr.overflow)
1875                }
1876              }
1877            }
1878          })
1879          .margin({ top: 10 })
1880      }
1881      .width('100%')
1882    }
1883    .height('100%')
1884  }
1885}
1886```
1887
1888![](figures/styledstring_5.png)
1889
1890### 示例6(设置自定义绘制Span)
1891
1892该示例通过CustomSpan接口实现属性字符串设置自定义绘制Span。
1893
1894```ts
1895// xxx.ets
1896import { drawing } from '@kit.ArkGraphics2D'
1897import { LengthMetrics } from '@kit.ArkUI'
1898
1899let gUIContext: UIContext;
1900
1901class MyCustomSpan extends CustomSpan {
1902  constructor(word: string, width: number, height: number) {
1903    super();
1904    this.word = word;
1905    this.width = width;
1906    this.height = height;
1907  }
1908
1909  onMeasure(measureInfo: CustomSpanMeasureInfo): CustomSpanMetrics {
1910    return { width: this.width, height: this.height };
1911  }
1912
1913  onDraw(context: DrawContext, options: CustomSpanDrawInfo) {
1914    let canvas = context.canvas;
1915
1916    const brush = new drawing.Brush();
1917    brush.setColor({
1918      alpha: 255,
1919      red: 0,
1920      green: 74,
1921      blue: 175
1922    });
1923    const font = new drawing.Font();
1924    font.setSize(25);
1925    const textBlob = drawing.TextBlob.makeFromString(this.word, font, drawing.TextEncoding.TEXT_ENCODING_UTF8);
1926    canvas.attachBrush(brush);
1927    canvas.drawRect({
1928      left: options.x + 10,
1929      right: options.x + gUIContext.vp2px(this.width) - 10,
1930      top: options.lineTop + 10,
1931      bottom: options.lineBottom - 10
1932    });
1933
1934    brush.setColor({
1935      alpha: 255,
1936      red: 23,
1937      green: 169,
1938      blue: 141
1939    });
1940    canvas.attachBrush(brush);
1941    canvas.drawTextBlob(textBlob, options.x + 20, options.lineBottom - 15);
1942    canvas.detachBrush();
1943  }
1944
1945  setWord(word: string) {
1946    this.word = word;
1947  }
1948
1949  width: number = 160;
1950  word: string = "drawing";
1951  height: number = 10;
1952}
1953
1954@Entry
1955@Component
1956struct styled_string_demo6 {
1957  customSpan1: MyCustomSpan = new MyCustomSpan("Hello", 80, 10);
1958  customSpan2: MyCustomSpan = new MyCustomSpan("World", 80, 40);
1959  style: MutableStyledString = new MutableStyledString(this.customSpan1);
1960  textStyle: MutableStyledString = new MutableStyledString("123");
1961  textController: TextController = new TextController();
1962  isPageShow: boolean = true;
1963
1964  aboutToAppear() {
1965    gUIContext = this.getUIContext();
1966  }
1967
1968  async onPageShow() {
1969    if (!this.isPageShow) {
1970      return
1971    }
1972    this.isPageShow = false;
1973
1974    this.style.appendStyledString(new MutableStyledString("文本绘制 示例代码 CustomSpan", [
1975      {
1976        start: 0,
1977        length: 5,
1978        styledKey: StyledStringKey.FONT,
1979        styledValue: new TextStyle({ fontColor: Color.Pink })
1980      }, {
1981      start: 5,
1982      length: 5,
1983      styledKey: StyledStringKey.FONT,
1984      styledValue: new TextStyle({ fontColor: Color.Orange, fontStyle: FontStyle.Italic })
1985    }, {
1986      start: 10,
1987      length: 500,
1988      styledKey: StyledStringKey.FONT,
1989      styledValue: new TextStyle({ fontColor: Color.Green, fontWeight: FontWeight.Bold })
1990    }
1991    ]))
1992    this.style.appendStyledString(new StyledString(this.customSpan2))
1993    this.style.appendStyledString(new StyledString("自定义绘制", [{
1994      start: 0,
1995      length: 5,
1996      styledKey: StyledStringKey.FONT,
1997      styledValue: new TextStyle({ fontColor: Color.Green, fontSize: LengthMetrics.px(50) })
1998    }]))
1999    this.textController.setStyledString(this.style)
2000  }
2001
2002  build() {
2003    Row() {
2004      Column() {
2005        Text(undefined, { controller: this.textController })
2006          .copyOption(CopyOptions.InApp)
2007          .fontSize(30)
2008
2009        Button("invalidate").onClick(() => {
2010          this.customSpan1.setWord("你好")
2011          this.customSpan1.invalidate()
2012        })
2013      }
2014      .width('100%')
2015    }
2016    .height('100%')
2017  }
2018}
2019```
2020
2021![](figures/styledstring_6.gif)
2022
2023### 示例7(支持存储自定义扩展信息)
2024
2025该示例通过UserDataSpan接口实现属性字符串支持存储自定义扩展信息的功能。
2026
2027```ts
2028// xxx.ets
2029class MyUserDateSpan extends UserDataSpan {
2030  constructor(name: string, age: number) {
2031    super()
2032    this.name = name
2033    this.age = age
2034  }
2035
2036  name: string
2037  age: number
2038}
2039
2040@Entry
2041@Component
2042struct styled_string_demo7 {
2043  @State name: string = "world"
2044  @State age: number = 10
2045  controller: TextController = new TextController()
2046  styleString: MutableStyledString = new MutableStyledString("hello world", [{
2047    start: 0,
2048    length: 11,
2049    styledKey: StyledStringKey.USER_DATA,
2050    styledValue: new MyUserDateSpan("hello", 21)
2051  }])
2052
2053  onPageShow(): void {
2054    this.controller.setStyledString(this.styleString)
2055  }
2056
2057  build() {
2058    Column() {
2059      Text(undefined, { controller: this.controller })
2060      Button("get user data").onClick(() => {
2061        let arr = this.styleString.getStyles(0, this.styleString.length)
2062        let userDataSpan = arr[0].styledValue as MyUserDateSpan
2063        this.name = userDataSpan.name
2064        this.age = userDataSpan.age
2065      })
2066      Text("name:" + this.name + "  age: " + this.age)
2067    }.width('100%').height(250).padding({ left: 35, right: 35, top: 35 })
2068  }
2069}
2070```
2071
2072![](figures/styledstring_7.gif)
2073
2074
2075### 示例8(支持转换HTML格式字符串)
2076
2077该示例通过toHtml、fromHtml接口实现属性字符串与HTML格式字符串的相关转换。
2078
2079```ts
2080// xxx.ets
2081import { image } from '@kit.ImageKit'
2082import { LengthMetrics } from '@kit.ArkUI'
2083
2084@Entry
2085@Component
2086struct styled_string_demo8 {
2087  imagePixelMap: image.PixelMap | undefined = undefined
2088  @State html : string | undefined = undefined
2089  @State styledString : StyledString | undefined = undefined
2090  controller1 : TextController = new TextController
2091  controller2 : TextController = new TextController
2092
2093  async aboutToAppear() {
2094    console.info("aboutToAppear initial imagePixelMap")
2095    this.imagePixelMap = await this.getPixmapFromMedia($r('app.media.icon'))
2096  }
2097
2098  private async getPixmapFromMedia(resource: Resource) {
2099    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
2100      bundleName: resource.bundleName,
2101      moduleName: resource.moduleName,
2102      id: resource.id
2103    })
2104    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
2105    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
2106      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
2107    })
2108    await imageSource.release()
2109    return createPixelMap
2110  }
2111
2112  build() {
2113    Column() {
2114      Text(undefined, { controller: this.controller1 }).height(100)
2115      Row() {
2116        Button("添加属性字符串").onClick(() => {
2117          let mutableStyledString1: MutableStyledString = new MutableStyledString("属性字符串", [{
2118            start: 0,
2119            length: 6,
2120            styledKey: StyledStringKey.FONT,
2121            styledValue: new TextStyle({ fontColor: Color.Green, fontSize: LengthMetrics.px(50) })
2122          }]);
2123          if (this.imagePixelMap !== undefined) {
2124            let mutableStyledString2 = new MutableStyledString(new ImageAttachment({
2125              value: this.imagePixelMap,
2126              size: { width: 50, height: 50 },
2127            }))
2128            mutableStyledString1.appendStyledString(mutableStyledString2)
2129          }
2130          this.styledString = mutableStyledString1
2131          this.controller1.setStyledString(mutableStyledString1)
2132        }).margin(5)
2133        Button("toHtml").onClick(() => {
2134          this.html = StyledString.toHtml(this.styledString)
2135        }).margin(5)
2136        Button("fromHtml").onClick(async () => {
2137          let styledString = await StyledString.fromHtml(this.html)
2138          this.controller2.setStyledString(styledString)
2139        }).margin(5)
2140      }
2141      Text(undefined, { controller: this.controller2 }).height(100)
2142      Text(this.html)
2143    }.width("100%")
2144  }
2145}
2146```
2147
2148![](figures/styledString_8.gif)
2149
2150
2151### 示例9(设置超链接)
2152
2153该示例通过UrlStyle接口,实现了对属性字符串中超链接设置的支持。
2154
2155```ts
2156// xxx.ets
2157@Entry
2158@Component
2159struct styled_string {
2160  urlString: StyledStringValue = new UrlStyle( "https://www.example.com" );
2161  mutableStyledString: MutableStyledString = new MutableStyledString("Hello World", [{
2162    start: 0,
2163    length: "Hello".length,
2164    styledKey: StyledStringKey.URL,
2165    styledValue: this.urlString
2166  }]);
2167  controller: TextController = new TextController();
2168  async onPageShow() {
2169    this.controller.setStyledString(this.mutableStyledString)
2170  }
2171  build() {
2172    Column() {
2173      Column() {
2174        Text(undefined, { controller: this.controller }).key('mutableStyledString').fontSize(30)
2175      }
2176    }.width('100%').height(250).padding({ left: 35, right: 35, top: 35 })
2177  }
2178}
2179```
2180
2181![](figures/styledString_9.gif)
2182
2183
2184### 示例10 (给图片设置colorFilter)
2185
2186该示例通过给imageAttachment设置colorFilter实现了给图像设置颜色滤镜效果。
2187
2188``` ts
2189// xxx.ets
2190import { LengthMetrics } from '@kit.ArkUI'
2191import { drawing, common2D } from '@kit.ArkGraphics2D';
2192@Entry
2193@Component
2194struct styled_string_demo4 {
2195  @State message: string = 'Hello World'
2196  mutableStr: MutableStyledString = new MutableStyledString('origin image:');
2197  mutableStr2: MutableStyledString = new MutableStyledString('with filter:');
2198  controller: TextController = new TextController();
2199  controller2: TextController = new TextController();
2200  private color: common2D.Color = { alpha: 125, red: 125, green: 125, blue: 255 };
2201  build() {
2202    Row() {
2203      Column({ space: 5 }) {
2204        Text(undefined, { controller: this.controller })
2205          .copyOption(CopyOptions.InApp)
2206          .draggable(true)
2207          .fontSize(30)
2208          .onAppear(() => {
2209            this.mutableStr = new MutableStyledString(new ImageAttachment({
2210              resourceValue: $r('app.media.startIcon'),
2211              size: { width: 50, height: 50 },
2212              layoutStyle: { borderRadius: LengthMetrics.vp(10) },
2213              verticalAlign: ImageSpanAlignment.BASELINE,
2214              objectFit: ImageFit.Contain,
2215              syncLoad: true
2216            }))
2217            this.controller.setStyledString(this.mutableStr)
2218          })
2219        Text(undefined, { controller: this.controller2 })
2220          .copyOption(CopyOptions.InApp)
2221          .draggable(true)
2222          .fontSize(30)
2223        Button('set image color filter')
2224          .onClick(() => {
2225            this.mutableStr2 = new MutableStyledString(new ImageAttachment({
2226              resourceValue: $r('app.media.startIcon'),
2227              size: { width: 50, height: 50 },
2228              layoutStyle: { borderRadius: LengthMetrics.vp(10) },
2229              verticalAlign: ImageSpanAlignment.BASELINE,
2230              objectFit: ImageFit.Contain,
2231              colorFilter: drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN),
2232              syncLoad: true
2233            }))
2234            this.controller2.setStyledString(this.mutableStr2)
2235          })
2236      }
2237      .width('100%')
2238    }
2239    .height('100%')
2240  }
2241}
2242```
2243
2244![](figures/styledString_10.gif)
2245
2246### 示例11(属性字符串的插入、删除、替换)
2247
2248该示例通过getSubStyledString、removeString、removeStyle、clearStyles、replaceStyledString、insertStyledString接口实现属性字符串的插入、删除、替换。
2249
2250``` ts
2251// xxx.ets
2252@Entry
2253@Component
2254struct styled_string_demo4 {
2255  @State message: string = 'Hello World'
2256  mutableStr: MutableStyledString = new MutableStyledString('123456', [{
2257    start: 0,
2258    length: 2,
2259    styledKey: StyledStringKey.FONT,
2260    styledValue: new TextStyle({fontColor: Color.Red})
2261  }, {
2262    start: 0,
2263    length: 3,
2264    styledKey: StyledStringKey.DECORATION,
2265    styledValue: new DecorationStyle({type: TextDecorationType.LineThrough})
2266  }]);
2267  mutableStr2: MutableStyledString = new MutableStyledString('with filter:');
2268  controller: TextController = new TextController();
2269  controller2: TextController = new TextController();
2270  build() {
2271    Row() {
2272      Column({ space: 5 }) {
2273        Text(undefined, { controller: this.controller })
2274          .copyOption(CopyOptions.InApp)
2275          .draggable(true)
2276          .fontSize(30)
2277          .onAppear(() => {
2278            this.controller.setStyledString(this.mutableStr)
2279          })
2280        Text(undefined, { controller: this.controller2 })
2281          .copyOption(CopyOptions.InApp)
2282          .draggable(true)
2283          .fontSize(30)
2284        Button('GetSubStyledString (0,3)').onClick(() => {
2285          this.controller2.setStyledString(this.mutableStr.subStyledString(0, 3))
2286        })
2287        Button('RemoveStyle (0,1,Decoration)').onClick(() => {
2288          this.mutableStr.removeStyle(0, 1, StyledStringKey.DECORATION)
2289          this.controller.setStyledString(this.mutableStr)
2290        })
2291        Button('RemoveString (5,1)').onClick(() => {
2292          this.mutableStr.removeString(5, 1)
2293          this.controller.setStyledString(this.mutableStr)
2294        })
2295        Button('ClearStyles').onClick(() => {
2296          this.mutableStr.clearStyles()
2297          this.controller.setStyledString(this.mutableStr)
2298        })
2299        Button('replaceStyledString').onClick(() => {
2300          this.mutableStr.replaceStyledString(3, 1, new StyledString("abc", [{
2301            start: 0,
2302            length: 3,
2303            styledKey: StyledStringKey.FONT,
2304            styledValue: new TextStyle({fontColor: Color.Blue})
2305          }]))
2306          this.controller.setStyledString(this.mutableStr)
2307        })
2308        Button('insertStyledString').onClick(() => {
2309          this.mutableStr.insertStyledString(4, new StyledString("A"))
2310          this.controller.setStyledString(this.mutableStr)
2311        })
2312      }
2313      .width('100%')
2314    }
2315    .height('100%')
2316  }
2317}
2318```
2319
2320![](figures/styledString_11.gif)
2321
2322
2323
2324
2325
2326
2327
2328
2329