• 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
20constructor(value: string | ImageAttachment | CustomSpan , styles?: Array\<StyleOptions>)
21
22**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
23
24**系统能力:** SystemCapability.ArkUI.ArkUI.Full
25
26**参数:**
27
28| 参数名 | 类型 | 必填 | 说明 |
29| -------- | -------- | -------- | -------- |
30| value | string \| [ImageAttachment](#imageattachment) \| [CustomSpan](#customspan) | 是 | 属性字符串文本内容。<br/>**说明:** <br/>当value值为ImageAttachment或CustomSpan时,styles参数不生效。  |
31| styles | Array<[StyleOptions](#styleoptions对象说明)> | 否 | 属性字符串初始化选项。<br/>**说明:** <br/>start为异常值时,按默认值0处理。<br/>当start的值合法且length为异常值时,length的值为属性字符串长度与start的值的差值。<br/>StyledStringKey与StyledStringValue不匹配时,不生效。<br/>styledKey参数无默认值。 |
32
33### 属性
34
35**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
36
37**系统能力:** SystemCapability.ArkUI.ArkUI.Full
38
39| 名称  |   类型   |   只读   |   可选   |   说明   |
40| ------ | ------ | ------ | ------ | -------------- |
41| length | number |  是   | 否   | 属性字符串字符的长度。<br/>**说明:** <br/>当属性字符串中包含图片或者CustomSpan时,其返回的长度按1计算。 |
42
43### getString
44
45getString(): string
46
47获取字符串信息。
48
49**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
50
51**系统能力:** SystemCapability.ArkUI.ArkUI.Full
52
53**返回值:**
54
55| 类型              |说明       |
56| ------- | --------------------------------- |
57| string | 属性字符串文本内容。<br/>**说明:** <br/>当属性字符串中包含图片时,其返回的结果用空格表示。 |
58
59### equals
60
61equals(other: StyledString): boolean
62
63判断两个属性字符串是否相等。
64
65**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
66
67**系统能力:** SystemCapability.ArkUI.ArkUI.Full
68
69**参数:**
70
71| 参数名  | 类型                              | 必填 | 说明                                                         |
72| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
73| other | [StyledString](#styledstring) | 是   | StyledString类型的比较对象。 |
74
75**返回值:**
76
77| 类型              |       说明       |
78| ------- | --------------------------------- |
79| boolean | 两个属性字符串是否相等。<br/>**说明:** <br/>当属性字符串的文本及样式均一致,视为相等。<br/>不比较GestureStyle,当属性字符串配置了不同事件,文本和其他样式相同时,亦视为相等。<br/>当比较CustomSpan时,比较的是地址,地址相等,视为相等。 |
80
81### subStyledString
82
83subStyledString(start: number , length?: number): StyledString
84
85获取属性字符串的子字符串。
86
87**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
88
89**系统能力:** SystemCapability.ArkUI.ArkUI.Full
90
91**参数:**
92
93| 参数名  | 类型                              | 必填 | 说明                                                         |
94| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
95| start | number | 是   | 子属性字符串开始位置的下标。 |
96| length | number | 否   | 子属性字符串的长度。 |
97
98**返回值:**
99
100| 类型              |       说明       |
101| ------- | --------------------------------- |
102| [StyledString](#styledstring) | 子属性字符串。<br/>**说明:** <br/>当start为合法入参时,length的默认值是被查询属性字符串对象的长度与start的值的差。<br/>当start和length越界或者必填传入undefined时,会抛出异常。|
103
104**错误码**:
105
106以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
107
108| 错误码ID | 错误信息 |
109| ------- | -------- |
110| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
111
112### getStyles
113
114getStyles(start: number , length: number , styledKey?: StyledStringKey): Array\<SpanStyle>
115
116获取指定范围属性字符串的样式集合。
117
118**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
119
120**系统能力:** SystemCapability.ArkUI.ArkUI.Full
121
122**参数:**
123
124| 参数名  | 类型                              | 必填 | 说明                                                         |
125| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
126| start | number | 是   | 指定范围属性字符串的下标。 |
127| length | number | 是   | 指定范围属性字符串的长度。 |
128| styledKey | [StyledStringKey](#styledstringkey12枚举说明) | 否   | 指定范围属性字符串样式的枚举值。 |
129
130**返回值:**
131
132| 类型              |       说明       |
133| ------- | --------------------------------- |
134| Array<[SpanStyle](#spanstyle对象说明)> | 各样式对象的数组。<br/>**说明:** <br/>当指定范围属性字符串未设置任何样式,则返回空数组。<br/>当start和length越界或者必填传入undefined时,会抛出异常;<br/>当styledKey传入异常值或undefined时,会抛出异常。<br/>当styledKey为CustomSpan时,返回的是创建CustomSpan时传入的样式对象,即修改该样式对象也会影响实际的显示效果。 |
135
136**错误码**:
137
138以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
139
140| 错误码ID | 错误信息 |
141| ------- | -------- |
142| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
143
144### fromHtml
145
146static fromHtml(html: string): Promise\<StyledString>
147
148将HTML格式字符串转换成属性字符串,当前支持转换的HTML标签范围:\<p>、\<span>、\<img>。仅支持将这三种标签中的style属性样式转换成对应的属性字符串样式。
149
150**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
151
152**系统能力:** SystemCapability.ArkUI.ArkUI.Full
153
154**参数:**
155
156| 参数名  | 类型                              | 必填 | 说明                                                         |
157| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
158| html | string | 是   | html格式的字符串。 |
159
160**返回值:**
161
162| 类型              |       说明       |
163| ------- | --------------------------------- |
164| [StyledString](#styledstring) | 属性字符串。 |
165
166**错误码**:
167
168以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
169
170| 错误码ID | 错误信息 |
171| ------- | -------- |
172| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
173
174## MutableStyledString
175
176继承于[StyledString](#styledstring)类。
177
178>  **以下接口异常入参处理统一说明:**
179>
180> 当start和length越界或者必填传入undefined时,会抛出异常;
181>
182> 当styledKey和styledValue传入异常值或者两者对应关系不匹配时,会抛出异常。
183>
184
185### replaceString
186
187replaceString(start: number , length: number , other: string): void
188
189替换指定范围的字符串。
190
191**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
192
193**系统能力:** SystemCapability.ArkUI.ArkUI.Full
194
195**参数:**
196
197| 参数名  | 类型                              | 必填 | 说明                                                         |
198| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
199| start | number | 是   | 指定范围的下标。 |
200| length | number | 是   | 指定范围的长度。 |
201| other | string | 是   | 替换的新文本内容。<br/>**说明:** <br/>替换的字符串使用的是start位置字符的样式。 |
202
203**错误码**:
204
205以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
206
207| 错误码ID | 错误信息 |
208| ------- | -------- |
209| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
210
211### insertString
212
213insertString(start: number , other: string): void
214
215插入字符串。
216
217**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
218
219**系统能力:** SystemCapability.ArkUI.ArkUI.Full
220
221**参数:**
222
223| 参数名  | 类型                              | 必填 | 说明                                                         |
224| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
225| start | number | 是   | 插入位置的下标。 |
226| other | string | 是   | 插入的新文本内容。<br/>**说明:** <br/>插入的字符串使用的是start-1位置字符的样式。若start-1位置字符未设置样式,则使用start位置字符样式。 |
227
228**错误码**:
229
230以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
231
232| 错误码ID | 错误信息 |
233| ------- | -------- |
234| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
235
236### removeString
237
238removeString(start: number , length: number): void
239
240移除指定范围的字符串。
241
242当属性字符串中包含图片时,同样生效。
243
244**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
245
246**系统能力:** SystemCapability.ArkUI.ArkUI.Full
247
248**参数:**
249
250| 参数名  | 类型                              | 必填 | 说明                                                         |
251| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
252| start | number | 是   | 指定范围的下标。 |
253| length | number | 是   | 指定范围的长度。 |
254
255**错误码**:
256
257以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
258
259| 错误码ID | 错误信息 |
260| ------- | -------- |
261| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
262
263### replaceStyle
264
265replaceStyle(spanStyle: SpanStyle): void
266
267替换指定范围内容为指定类型新样式。
268
269**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
270
271**系统能力:** SystemCapability.ArkUI.ArkUI.Full
272
273**参数:**
274
275| 参数名  | 类型                              | 必填 | 说明                                                         |
276| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
277| spanStyle | [SpanStyle](#spanstyle对象说明) | 是   | 样式对象。<br/>**说明:** <br/>默认清空原有样式,替换为新样式。<br/>当SpanStyle的styledKey为IMAGE或CUSTOM_SPAN时,只有当start的位置当前是image或CustomSpan且长度为1,才会生效,其余情况无效果。 |
278
279**错误码**:
280
281以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
282
283| 错误码ID | 错误信息 |
284| ------- | -------- |
285| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
286
287### setStyle
288
289setStyle(spanStyle: SpanStyle): void
290
291为指定范围内容设置指定类型新样式。
292
293**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
294
295**系统能力:** SystemCapability.ArkUI.ArkUI.Full
296
297**参数:**
298
299| 参数名  | 类型                              | 必填 | 说明                                                         |
300| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
301| spanStyle | [SpanStyle](#spanstyle对象说明) | 是   | 样式对象。<br/>**说明:** <br/>默认不清空原有样式,叠加新样式。若是已有样式,则更新。<br/>当SpanStyle的styledKey为IMAGE或CUSTOM_SPAN时,只有当start的位置当前是image或者CustomSpan且长度为1,才会生效,其余情况无效果。 |
302
303**错误码**:
304
305以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
306
307| 错误码ID | 错误信息 |
308| ------- | -------- |
309| 401      |The parameter check failed.   |
310
311### removeStyle
312
313removeStyle(start: number , length: number , styledKey: StyledStringKey): void
314
315清除指定范围内容的指定类型样式。
316
317被清空样式类型对象属性使用的是对应[Text](./ts-basic-components-text.md)组件属性的设置值,若Text组件未设置值,则使用对应Text组件属性的默认值。
318
319当属性字符串中包含图片时,同样生效。
320
321**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
322
323**系统能力:** SystemCapability.ArkUI.ArkUI.Full
324
325**参数:**
326
327| 参数名  | 类型                              | 必填 | 说明                                                         |
328| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
329| start | number | 是   | 指定范围开始位置的下标。 |
330| length | number | 是   | 指定范围的长度。 |
331| styledKey | [StyledStringKey](#styledstringkey12枚举说明) | 是   | 样式类型枚举值。 |
332
333**错误码**:
334
335以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
336
337| 错误码ID | 错误信息 |
338| ------- | -------- |
339| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
340
341### removeStyles
342
343removeStyles(start: number , length: number): void
344
345清除指定范围内容的所有样式。
346
347被清空样式类型对象属性使用的是对应[Text](./ts-basic-components-text.md)组件属性的设置值,若Text组件未设置值,则使用对应Text组件属性的默认值。
348
349当属性字符串中包含图片时,同样生效。
350
351**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
352
353**系统能力:** SystemCapability.ArkUI.ArkUI.Full
354
355**参数:**
356
357| 参数名  | 类型                              | 必填 | 说明                                                         |
358| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
359| start | number | 是   | 指定范围开始位置的下标。 |
360| length | number | 是   | 指定范围的长度。 |
361
362**错误码**:
363
364以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
365
366| 错误码ID | 错误信息 |
367| ------- | -------- |
368| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
369
370### clearStyles
371
372clearStyles(): void
373
374清除属性字符串对象的所有样式。
375
376被清空样式类型对象属性使用的是对应[Text](./ts-basic-components-text.md)组件属性的设置值,若Text组件未设置值,则使用对应Text组件属性的默认值。
377
378**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
379
380**系统能力:** SystemCapability.ArkUI.ArkUI.Full
381
382### replaceStyledString
383
384replaceStyledString(start: number , length: number , other: StyledString): void
385
386替换指定范围为新的属性字符串。
387
388**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
389
390**系统能力:** SystemCapability.ArkUI.ArkUI.Full
391
392**参数:**
393
394| 参数名  | 类型                              | 必填 | 说明                                                         |
395| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
396| start | number | 是   | 指定范围开始位置的下标。 |
397| length | number | 是   | 指定范围的长度。 |
398| other | [StyledString](#styledstring) | 是   | 新的属性字符串对象。 |
399
400**错误码**:
401
402以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
403
404| 错误码ID | 错误信息 |
405| ------- | -------- |
406| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
407
408### insertStyledString
409
410insertStyledString(start: number , other: StyledString): void
411
412在指定位置插入新的属性字符串。
413
414**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
415
416**系统能力:** SystemCapability.ArkUI.ArkUI.Full
417
418**参数:**
419
420| 参数名  | 类型                              | 必填 | 说明                                                         |
421| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
422| start | number | 是   | 开始插入位置的下标。 |
423| other | [StyledString](#styledstring) | 是   | 新的属性字符串对象。|
424
425**错误码**:
426
427以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)。
428
429| 错误码ID | 错误信息 |
430| ------- | -------- |
431| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
432
433### appendStyledString
434
435appendStyledString(other: StyledString): void
436
437在末尾位置追加新的属性字符串。
438
439**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
440
441**系统能力:** SystemCapability.ArkUI.ArkUI.Full
442
443**参数:**
444
445| 参数名  | 类型                              | 必填 | 说明                                                         |
446| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
447| other | [StyledString](#styledstring) | 是   | 新的属性字符串对象。|
448
449## StyleOptions对象说明
450
451**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
452
453**系统能力:** SystemCapability.ArkUI.ArkUI.Full
454
455| 名称  | 类型                              | 必填 | 说明   |
456| ------- | --------------------------------- | ---- | --------------------------------- |
457| start | number | 否   | 设置属性字符串样式的开始位置。 |
458| length | number | 否   | 设置属性字符串样式的长度。 |
459| styledKey | [StyledStringKey](#styledstringkey12枚举说明) | 是   | 样式类型的枚举值。 |
460| styledValue | [StyledStringValue](ts-types.md#styledstringvalue12) | 是   | 样式对象。 |
461
462## SpanStyle对象说明
463
464**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
465
466**系统能力:** SystemCapability.ArkUI.ArkUI.Full
467
468| 名称  | 类型                              | 必填 | 说明   |
469| ------- | --------------------------------- | ---- | --------------------------------- |
470| start | number | 是   | 匹配属性字符串样式的开始位置。 |
471| length | number | 是   | 匹配属性字符串样式的长度。 |
472| styledKey | [StyledStringKey](#styledstringkey12枚举说明) | 是   | 样式类型的枚举值。 |
473| styledValue | [StyledStringValue](ts-types.md#styledstringvalue12) | 是   | 样式对象。 |
474
475## TextStyle
476
477文本字体样式对象说明。
478
479**系统能力:** SystemCapability.ArkUI.ArkUI.Full
480
481### 属性
482
483**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
484
485**系统能力:** SystemCapability.ArkUI.ArkUI.Full
486
487| 名称           | 类型              | 只读   | 可选   | 说明     |
488| ------------ |---------------------| ---- | ---- | ------ |
489| fontColor  | [ResourceColor](ts-types.md#resourcecolor) |  是  |  是  | 获取属性字符串的文本颜色。 |
490| fontFamily | string   | 是    | 是   | 获取属性字符串的文本字体。 |
491| fontSize   | number   | 是    | 是    | 获取属性字符串的文本字体大小。<br/>单位:fp |
492| fontWeight   | number   | 是    | 是    | 获取属性字符串的文本字体粗细。 |
493| fontStyle   | [FontStyle](ts-appendix-enums.md#fontstyle) | 是    | 是    | 获取属性字符串的文本字体样式。 |
494
495### constructor
496
497constructor(value?: TextStyleInterface)
498
499**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
500
501**系统能力:** SystemCapability.ArkUI.ArkUI.Full
502
503**参数:**
504
505| 参数名  | 类型                              | 必填 | 说明   |
506| ------- | --------------------------------- | ---- | --------------------------------- |
507| value | [TextStyleInterface](#textstyleinterface对象说明) | 否   | 字体样式设置项。 |
508
509## TextStyleInterface对象说明
510
511**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
512
513**系统能力:** SystemCapability.ArkUI.ArkUI.Full
514
515| 名称  | 类型                              | 必填 | 说明   |
516| ------- | --------------------------------- | ---- | --------------------------------- |
517| fontColor | [ResourceColor](ts-types.md#resourcecolor) | 否   | 字体颜色。 |
518| fontFamily | [ResourceStr](ts-types.md#resourcestr) | 否   | 文本字体。 |
519| fontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 否   | 字体大小。如果LengthMetrics的unit值是percent,当前设置不生效,处理为16fp。 |
520| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | 否   | 字体粗细。 |
521| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | 否   | 字体样式。 |
522
523## GestureStyle
524
525事件手势对象说明。
526
527**系统能力:** SystemCapability.ArkUI.ArkUI.Full
528
529### constructor
530
531constructor(value?: GestureStyleInterface)
532
533**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
534
535**系统能力:** SystemCapability.ArkUI.ArkUI.Full
536
537**参数:**
538
539| 参数名  | 类型                              | 必填 | 说明   |
540| ------- | --------------------------------- | ---- | --------------------------------- |
541| value | [GestureStyleInterface](#gesturestyleinterface对象说明) | 否   | 事件设置项。 |
542
543## GestureStyleInterface对象说明
544
545**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
546
547**系统能力:** SystemCapability.ArkUI.ArkUI.Full
548
549| 名称  | 类型                              | 必填 | 说明   |
550| ------- | --------------------------------- | ---- | --------------------------------- |
551| onClick | Callback\<[ClickEvent](ts-universal-events-click.md#clickevent对象说明)> | 否   | 设置点击事件。 |
552| onLongPress | Callback\<[GestureEvent](./ts-gesture-settings.md#gestureevent对象说明)> | 否   | 设置长按事件。 |
553
554## DecorationStyle
555
556文本装饰线样式对象说明。
557
558**系统能力:** SystemCapability.ArkUI.ArkUI.Full
559
560### 属性
561
562**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
563
564**系统能力:** SystemCapability.ArkUI.ArkUI.Full
565
566| 名称           | 类型              | 只读   |可选   | 说明     |
567| ------------ |---------------------| ---- | ---- | ------ |
568| type  | [TextDecorationType](ts-appendix-enums.md#textdecorationtype) |  是  |  否  | 获取属性字符串的文本装饰线类型。 |
569| color | [ResourceColor](ts-types.md#resourcecolor)   | 是    | 是  | 获取属性字符串的文本装饰线颜色。 |
570| style | [TextDecorationStyle](ts-appendix-enums.md#textdecorationstyle12) | 是    |是  | 获取属性字符串的文本装饰线样式。 |
571
572### constructor
573
574constructor(value: DecorationStyleInterface)
575
576**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
577
578**系统能力:** SystemCapability.ArkUI.ArkUI.Full
579
580**参数:**
581
582| 参数名  | 类型                              | 必填 | 说明   |
583| ------- | --------------------------------- | ---- | --------------------------------- |
584| value | [DecorationStyleInterface](#decorationstyleinterface对象说明) | 是   | 文本装饰线设置项。 |
585
586## DecorationStyleInterface对象说明
587
588**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
589
590**系统能力:** SystemCapability.ArkUI.ArkUI.Full
591
592| 名称  | 类型                              | 必填 | 说明   |
593| ------- | --------------------------------- | ---- | --------------------------------- |
594| type | [TextDecorationType](ts-appendix-enums.md#textdecorationtype) | 是   | 装饰线类型。 |
595| color | [ResourceColor](ts-types.md#resourcecolor) | 否   | 装饰线颜色。 |
596| style | [TextDecorationStyle](ts-appendix-enums.md#textdecorationstyle12) | 否   | 装饰线样式。 |
597
598## BaselineOffsetStyle
599
600文本基线偏移量对象说明。
601
602**系统能力:** SystemCapability.ArkUI.ArkUI.Full
603
604### 属性
605
606**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
607
608**系统能力:** SystemCapability.ArkUI.ArkUI.Full
609
610| 名称           | 类型              | 只读   | 可选   | 说明     |
611| ------------ |---------------------| ---- | ---- | ------ |
612| baselineOffset  | number |  是  |  否 | 获取属性字符串的文本基线偏移量。<br/>单位:vp |
613
614### constructor
615
616constructor(value: LengthMetrics)
617
618**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
619
620**系统能力:** SystemCapability.ArkUI.ArkUI.Full
621
622**参数:**
623
624| 参数名  | 类型                              | 必填 | 说明   |
625| ------- | --------------------------------- | ---- | --------------------------------- |
626| value | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 是   | 文本基线偏移量设置项。如果LengthMetrics的unit值是percent,该设置不生效。 |
627
628## LetterSpacingStyle
629
630文本字符间距对象说明。
631
632**系统能力:** SystemCapability.ArkUI.ArkUI.Full
633
634### 属性
635
636**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
637
638**系统能力:** SystemCapability.ArkUI.ArkUI.Full
639
640| 名称           | 类型              | 只读   | 可选   | 说明     |
641| ------------ |---------------------| ---- | ---- | ------ |
642| letterSpacing  | number |  是  |  否  | 获取属性字符串的文本字符间距。<br/>单位:vp |
643
644### constructor
645
646constructor(value: LengthMetrics)
647
648**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
649
650**系统能力:** SystemCapability.ArkUI.ArkUI.Full
651
652**参数:**
653
654| 参数名  | 类型                              | 必填 | 说明   |
655| ------- | --------------------------------- | ---- | --------------------------------- |
656| value | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 是   | 文本字符间距设置项。如果LengthMetrics的unit值是percent,该设置不生效。 |
657
658## LineHeightStyle
659
660文本行高对象说明。
661
662**系统能力:** SystemCapability.ArkUI.ArkUI.Full
663
664### 属性
665
666**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
667
668**系统能力:** SystemCapability.ArkUI.ArkUI.Full
669
670| 名称           | 类型              | 只读   | 可选   | 说明     |
671| ------------ |---------------------| ---- | ---- | ------ |
672| lineHeight  | number |  是  |  否  | 获取属性字符串的文本行高。<br/>单位:vp |
673
674### constructor
675
676constructor(lineHeight: LengthMetrics)
677
678**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
679
680**系统能力:** SystemCapability.ArkUI.ArkUI.Full
681
682**参数:**
683
684| 参数名  | 类型                              | 必填 | 说明   |
685| ------- | --------------------------------- | ---- | --------------------------------- |
686| lineHeight | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 是   | 文本行高设置项。如果LengthMetrics的value值不大于0时,不限制文本行高,自适应字体大小。 |
687
688## TextShadowStyle
689
690文本阴影对象说明。
691
692**系统能力:** SystemCapability.ArkUI.ArkUI.Full
693
694### 属性
695
696**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
697
698**系统能力:** SystemCapability.ArkUI.ArkUI.Full
699
700| 名称           | 类型              | 只读   | 可选   | 说明     |
701| ------------ |---------------------| ---- | ---- | ------ |
702| textShadow  | Array\<[ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明)> |  是  |  否  | 获取属性字符串的文本阴影。 |
703
704### constructor
705
706constructor(value: ShadowOptions | Array\<ShadowOptions>)
707
708**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
709
710**系统能力:** SystemCapability.ArkUI.ArkUI.Full
711
712**参数:**
713
714| 参数名  | 类型                              | 必填 | 说明   |
715| ------- | --------------------------------- | ---- | --------------------------------- |
716| value | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明) \| Array\<[ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明)>  | 是   | 文本阴影设置项。 |
717
718## ImageAttachment
719
720图片对象说明。
721
722**系统能力:** SystemCapability.ArkUI.ArkUI.Full
723
724### 属性
725
726**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
727
728**系统能力:** SystemCapability.ArkUI.ArkUI.Full
729
730| 名称           | 类型              | 只读   | 可选   | 说明     |
731| ------------ |---------------------| ---- | ---- | ------ |
732| value  | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) |  是  |  否  | 获取属性字符串的图片数据源。 |
733| size  | [SizeOptions](ts-types.md#sizeoptions) |  是  |  是  | 获取属性字符串的图片尺寸。 |
734| verticalAlign  | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) |  是  |  是  | 获取属性字符串的图片对齐方式。 |
735| objectFit  | [ImageFit](ts-appendix-enums.md#imagefit) |  是  |  是  | 获取属性字符串的图片缩放类型。 |
736| layoutStyle  | [ImageAttachmentLayoutStyle](#imageattachmentlayoutstyle对象说明) |  是  |  是  | 获取属性字符串的图片布局。 |
737
738### constructor
739
740constructor(value: ImageAttachmentInterface)
741
742**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
743
744**系统能力:** SystemCapability.ArkUI.ArkUI.Full
745
746**参数:**
747
748| 参数名  | 类型                              | 必填 | 说明   |
749| ------- | --------------------------------- | ---- | --------------------------------- |
750| value | [ImageAttachmentInterface](#imageattachmentinterface对象说明) | 是   | 图片设置项。 |
751
752## ImageAttachmentInterface对象说明
753
754**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
755
756**系统能力:** SystemCapability.ArkUI.ArkUI.Full
757
758| 名称  | 类型                              | 必填 | 说明   |
759| ------- | --------------------------------- | ---- | --------------------------------- |
760| value | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) |  是  | 设置图片数据源。 |
761| size | [SizeOptions](ts-types.md#sizeoptions) | 否   | 设置图片大小。 |
762| verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | 否   | 设置图片基于文本的对齐方式。 |
763| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 否   | 设置图片的缩放类型。 |
764| layoutStyle | [ImageAttachmentLayoutStyle](#imageattachmentlayoutstyle对象说明) | 否   | 设置图片布局。 |
765
766## ImageAttachmentLayoutStyle对象说明
767
768**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
769
770**系统能力:** SystemCapability.ArkUI.ArkUI.Full
771
772| 名称  | 类型                              | 必填 | 说明   |
773| ------- | --------------------------------- | ---- | --------------------------------- |
774| margin | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [Margin](ts-types.md#margin) | 否   | 设置图片外边距。 |
775| padding | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [Padding](ts-types.md#padding) | 否   | 设置图片内边距。 |
776| borderRadius | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [BorderRadiuses](ts-types.md#borderradiuses9) | 否   | 设置圆角。 |
777
778## CustomSpan
779
780自定义绘制Span,仅提供基类,具体实现由开发者定义。
781
782自定义绘制Span拖拽显示的缩略图为空白。
783
784**系统能力:** SystemCapability.ArkUI.ArkUI.Full
785
786### onMeasure
787
788abstract onMeasure(measureInfo: CustomSpanMeasureInfo): CustomSpanMetrics
789
790获取自定义绘制Span的尺寸大小。
791
792**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
793
794**系统能力:** SystemCapability.ArkUI.ArkUI.Full
795
796**参数:**
797
798| 参数名  | 类型                              | 必填 | 说明                                                         |
799| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
800| measureInfo | [CustomSpanMeasureInfo](#customspanmeasureinfo对象说明) | 是   | 文本的字体大小。 |
801
802**返回值:**
803
804| 类型              |       说明       |
805| ------- | --------------------------------- |
806| [CustomSpanMetrics](#customspanmetrics对象说明) | 自定义绘制Span的尺寸信息。<br/>**说明:** <br/>最终的CustomSpan的高度是由当前Text组件的行高所决定的。当height不传值,则默认取Text组件的fontSize的值作为CustomSpan的高度;当height大于当前行的其他子组件的高度时,此时height即为Text组件的行高。 |
807
808### onDraw
809
810abstract onDraw(context: DrawContext, drawInfo: CustomSpanDrawInfo): void
811
812绘制自定义绘制Span。
813
814**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
815
816**系统能力:** SystemCapability.ArkUI.ArkUI.Full
817
818**参数:**
819
820| 参数名  | 类型                              | 必填 | 说明                                                         |
821| ------- | --------------------------------- | ---- | ------------------------------------------------------------ |
822| context | [DrawContext](../js-apis-arkui-graphics.md#drawcontext) | 是   | 图形绘制上下文。<br/>**说明:** <br/>DrawContext的canvas方法获取的画布是Text组件的画布,绘制时不会超出Text组件的范围。 |
823| drawInfo | [CustomSpanDrawInfo](#customspandrawinfo对象说明) | 是   | 自定义绘制Span的绘制信息。 |
824
825### invalidate<sup>13+<sup>
826
827invalidate(): void
828
829主动刷新使用CustomSpan的Text组件。
830
831**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
832
833**系统能力:** SystemCapability.ArkUI.ArkUI.Full
834
835## CustomSpanMeasureInfo对象说明
836
837**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
838
839**系统能力:** SystemCapability.ArkUI.ArkUI.Full
840
841| 名称  | 类型                              | 必填 | 说明   |
842| ------- | --------------------------------- | ---- | --------------------------------- |
843| fontSize | number |  是  | 设置文本字体大小。<br/>单位:fp |
844
845## CustomSpanMetrics对象说明
846
847**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
848
849**系统能力:** SystemCapability.ArkUI.ArkUI.Full
850
851| 名称  | 类型                              | 必填 | 说明   |
852| ------- | --------------------------------- | ---- | --------------------------------- |
853| width | number |  是  | 自定义绘制Span的宽。<br/>单位:vp |
854| height | number |  否  | 自定义绘制Span的高。<br/>单位:vp |
855
856## CustomSpanDrawInfo对象说明
857
858**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
859
860**系统能力:** SystemCapability.ArkUI.ArkUI.Full
861
862| 名称  | 类型                              | 必填 | 说明   |
863| ------- | --------------------------------- | ---- | --------------------------------- |
864| x | number |  是  | 自定义绘制Span相对于挂载组件的偏移。<br/>单位:px |
865| lineTop | number |  是  | 自定义绘制Span相对于Text组件的上边距。<br/>单位:px |
866| lineBottom | number |  是  | 自定义绘制Span相对于Text组件的下边距。<br/>单位:px |
867| baseline | number |  是  | 自定义绘制Span的所在行的基线偏移量。<br/>单位:px |
868
869## ParagraphStyle
870
871文本段落样式对象说明。
872
873除首个段落外,后续段落按'\n'划分。
874
875每个段落的段落样式按首个占位设置的段落样式生效,未设置时,段落按被绑定组件的段落样式生效。
876
877**系统能力:** SystemCapability.ArkUI.ArkUI.Full
878
879### 属性
880
881**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
882
883**系统能力:** SystemCapability.ArkUI.ArkUI.Full
884
885| 名称           | 类型              | 只读   | 可选   | 说明     |
886| ------------ |---------------------| ---- | ---- | ------ |
887| textAlign  | [TextAlign](ts-appendix-enums.md#textalign) |  是  |  是  | 获取属性字符串文本段落在水平方向的对齐方式。 |
888| textIndent | number   | 是    | 是    | 获取属性字符串文本段落的首行文本缩进。 |
889| maxLines   | number   | 是    | 是    | 获取属性字符串文本段落的最大行数。 |
890| overflow   | [TextOverflow](ts-appendix-enums.md#textoverflow)   | 是    | 是   | 获取属性字符串文本段落超长时的显示方式。 |
891| wordBreak   | [WordBreak](ts-appendix-enums.md#wordbreak11) | 是    | 是    | 获取属性字符串文本段落的断行规则。 |
892| leadingMargin   | number \| [LeadingMarginPlaceholder](ts-basic-components-richeditor.md#leadingmarginplaceholder11) | 是    | 是   | 获取属性字符串文本段落的缩进。 |
893
894>  **说明:**
895>
896>  属性字符串的maxLines和overflow仅在Text中生效,建议在组件侧设置。
897
898### constructor
899
900constructor(value?: ParagraphStyleInterface)
901
902**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
903
904**系统能力:** SystemCapability.ArkUI.ArkUI.Full
905
906**参数:**
907
908| 参数名  | 类型                              | 必填 | 说明   |
909| ------- | --------------------------------- | ---- | --------------------------------- |
910| value | [ParagraphStyleInterface](#paragraphstyleinterface对象说明) | 否   | 段落样式设置项。 |
911
912## ParagraphStyleInterface对象说明
913
914**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
915
916**系统能力:** SystemCapability.ArkUI.ArkUI.Full
917
918| 名称  | 类型                              | 必填 | 说明   |
919| ------- | --------------------------------- | ---- | --------------------------------- |
920| textAlign  | [TextAlign](ts-appendix-enums.md#textalign) |  否  | 设置文本段落在水平方向的对齐方式。 |
921| textIndent | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12)   | 否    | 设置文本段落的首行文本缩进。 |
922| maxLines   | number   | 否    | 设置文本段落的最大行数。 |
923| overflow   | [TextOverflow](ts-appendix-enums.md#textoverflow)   |  否    | 设置文本段落超长时的显示方式。<br />需配合maxLines使用,单独设置不生效。不支持TextOverflow.MARQUEE。 |
924| wordBreak   | [WordBreak](ts-appendix-enums.md#wordbreak11) | 否    | 设置文本段落的断行规则。 |
925| leadingMargin   | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [LeadingMarginPlaceholder](ts-basic-components-richeditor.md#leadingmarginplaceholder11) | 否    | 设置文本段落的缩进。 |
926
927## UserDataSpan
928
929支持存储自定义扩展信息,用于存储和获取用户数据,仅提供基类,具体实现由开发者定义。
930
931扩展信息不影响实际显示效果。
932
933**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
934
935**系统能力:** SystemCapability.ArkUI.ArkUI.Full
936
937## StyledStringKey<sup>12+</sup>枚举说明
938
939**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
940
941**系统能力:** SystemCapability.ArkUI.ArkUI.Full
942
943| 名称     |说明                           |
944| ------ | ----------------------------- |
945| FONT | 字体样式键。[TextStyle](./ts-universal-styled-string.md#textstyle)所属键。|
946| DECORATION | 文本装饰线样式键。[DecorationStyle](./ts-universal-styled-string.md#decorationstyle)所属键。|
947| BASELINE_OFFSET | 文本基线偏移量样式键。[BaselineOffsetStyle](./ts-universal-styled-string.md#baselineoffsetstyle)所属键。|
948| LETTER_SPACING | 文本字符间距样式键。[LetterSpacingStyle](./ts-universal-styled-string.md#letterspacingstyle)所属键。|
949| LINE_HEIGHT | 文本行高样式键。[LineHeightStyle](./ts-universal-styled-string.md#lineheightstyle)所属键。|
950| TEXT_SHADOW | 文本阴影样式键。[TextShadowStyle](./ts-universal-styled-string.md#textshadowstyle)所属键。|
951| GESTURE | 事件手势键。[GestureStyle](./ts-universal-styled-string.md#gesturestyle)所属键。|
952| PARAGRAPH_STYLE | 段落样式键。[ParagraphStyle](./ts-universal-styled-string.md#paragraphstyle)所属键。|
953| IMAGE | 图片键。[ImageAttachment](./ts-universal-styled-string.md#imageattachment)所属键。|
954| CUSTOM_SPAN | 自定义绘制Span键。[CustomSpan](./ts-universal-styled-string.md#customspan)所属键。|
955| USER_DATA | UserDataSpan键。[UserDataSpan](./ts-universal-styled-string.md#userdataspan)所属键。|
956
957## 示例
958
959### 示例1
960
961属性字符串接口基本使用示例
962
963```ts
964// xxx.ets
965@Entry
966@Component
967struct styled_string_demo1 {
968  @State height1: number = 450;
969  @State fontSize1: number = 16;
970  @State fontWeight1: number = 400;
971  @State color1: Color = Color.Blue;
972  scroll: Scroller = new Scroller();
973  fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue });
974  fontStyleAttr2: StyledStringValue = new TextStyle({ fontColor: Color.Orange });
975  // 创建可读写属性字符串的对象mutableStyledString1
976  mutableStyledString1: MutableStyledString = new MutableStyledString("运动45分钟");
977  // 创建构造入参有字符串和样式的对象mutableStyledString2
978  mutableStyledString2: MutableStyledString = new MutableStyledString("test hello world", [{
979    start: 0,
980    length: 5,
981    styledKey: StyledStringKey.FONT,
982    styledValue: this.fontStyleAttr1
983  }]);
984  // 创建只读属性字符串对象styledString2
985  styledString2: StyledString = new StyledString("运动45分钟");
986  spanStyle1: SpanStyle = {
987    start: 0,
988    length: 5,
989    styledKey: StyledStringKey.FONT,
990    styledValue: new TextStyle({ fontColor: Color.Pink })
991  };
992  spanStyle2: SpanStyle = {
993    start: 0,
994    length: 2,
995    styledKey: StyledStringKey.FONT,
996    styledValue: new TextStyle({ fontColor: Color.Red })
997  };
998  @State string1: string = '';
999  @State fontColor1: ResourceColor = Color.Red;
1000  controller1: TextController = new TextController();
1001  controller2: TextController = new TextController();
1002  controller3: TextController = new TextController();
1003
1004  async onPageShow() {
1005    this.controller1.setStyledString(this.styledString2)
1006    this.controller2.setStyledString(this.mutableStyledString1)
1007    this.controller3.setStyledString(this.mutableStyledString2)
1008  }
1009
1010  build() {
1011    Column() {
1012      Scroll(this.scroll) {
1013        Column() {
1014          // 显示属性字符串
1015          Text(undefined, { controller: this.controller1 })
1016          Text(undefined, { controller: this.controller3 }).key('mutableStyledString2')
1017          Button('修改string1的值')
1018            .onClick(() => {
1019              let result = this.mutableStyledString1.equals(this.styledString2);
1020              if (result) {
1021                this.string1 = this.mutableStyledString1.getString();
1022                console.info("mutableStyledString1 content:", this.mutableStyledString1.getString());
1023                console.info("mutableStyledString1 length:", this.mutableStyledString1.length);
1024              }
1025            })
1026
1027          // 属性字符串与Span冲突时忽略Span,以及样式与Text组件属性未冲突部分生效Text设置的属性
1028          Text(undefined, { controller: this.controller2 }) {
1029            Span("span and styledString test")
1030              .fontColor(Color.Yellow)
1031              .decoration({ type: TextDecorationType.LineThrough })
1032            ImageSpan($r('app.media.icon'))
1033          }
1034          .key('styledString2')
1035          .fontColor(this.fontColor1)
1036          .letterSpacing(10)
1037          .fontSize(32)
1038          .fontWeight(600)
1039          .fontStyle(FontStyle.Italic)
1040          .lineHeight(30)
1041          .textShadow({ radius: 5, color: Color.Blue, offsetX: 5, offsetY: 5 })
1042          .textCase(TextCase.UpperCase)
1043          .decoration({ type: TextDecorationType.LineThrough, color: Color.Yellow })
1044          .baselineOffset(2)
1045          .copyOption(CopyOptions.InApp)
1046          .margin({ top: 10 })
1047          .draggable(true)
1048
1049          // 以上冲突测试对照组
1050          Text() {
1051            Span(this.string1)
1052              .fontColor(this.color1)
1053              .decoration({ type: TextDecorationType.LineThrough })
1054            ImageSpan($r('app.media.icon'))
1055              .width(50).height(50)
1056          }
1057          .letterSpacing(10)
1058          .fontSize(32)
1059          .fontWeight(600)
1060          .fontStyle(FontStyle.Italic)
1061          .lineHeight(30)
1062          .textShadow({ radius: 5, color: Color.Blue, offsetX: 5, offsetY: 5 })
1063          .textCase(TextCase.UpperCase)
1064          .decoration({ type: TextDecorationType.LineThrough, color: Color.Yellow })
1065          .baselineOffset(2)
1066
1067          Button('设置样式及替换文本')
1068            .onClick(() => {
1069              this.mutableStyledString1.replaceStyle({
1070                start: 2,
1071                length: 2,
1072                styledKey: StyledStringKey.FONT,
1073                styledValue: this.fontStyleAttr1
1074              })
1075              this.mutableStyledString1.insertString(0, "压力85偏高,")
1076              this.mutableStyledString1.setStyle({
1077                start: 2,
1078                length: 2,
1079                styledKey: StyledStringKey.FONT,
1080                styledValue: this.fontStyleAttr2
1081              })
1082              this.controller2.setStyledString(this.mutableStyledString1)
1083            })
1084            .margin({ top: 10 })
1085
1086          Button('查询样式及清空样式')
1087            .onClick(() => {
1088              let styles = this.mutableStyledString1.getStyles(0, this.mutableStyledString1.length)
1089              if (styles.length == 2) {
1090                for (let i = 0; i < styles.length; i++) {
1091                  console.info('StyledString style object start:' + styles[i].start)
1092                  console.info('StyledString style object length:' + styles[i].length)
1093                  console.info('StyledString style object key:' + styles[i].styledKey)
1094                  if (styles[i].styledKey === 0) {
1095                    let fontAttr = styles[i].styledValue as TextStyle;
1096                    console.info('StyledString fontColor:' + fontAttr.fontColor)
1097                  }
1098                }
1099              }
1100              if (styles[0] !== undefined) {
1101                this.mutableStyledString2.setStyle(styles[0]);
1102                this.controller3.setStyledString(this.mutableStyledString2);
1103              }
1104              this.mutableStyledString1.removeStyles(2, 3);
1105              this.controller2.setStyledString(this.mutableStyledString1);
1106            })
1107            .margin({ top: 10 })
1108        }.width('100%')
1109
1110      }
1111      .expandSafeArea([SafeAreaType.KEYBOARD])
1112      .scrollable(ScrollDirection.Vertical)
1113      .scrollBar(BarState.On)
1114      .scrollBarColor(Color.Gray)
1115      .scrollBarWidth(10)
1116      .edgeEffect(EdgeEffect.None)
1117    }
1118    .width('100%')
1119  }
1120}
1121```
1122
1123![](figures/styledstring_1.PNG)
1124
1125### 示例2
1126
1127属性字符串支持事件接口示例
1128
1129```ts
1130// xxx.ets
1131import { promptAction } from '@kit.ArkUI';
1132
1133@Entry
1134@Component
1135struct styled_string_demo2 {
1136  scroll: Scroller = new Scroller();
1137  fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue });
1138  clickGestureAttr: GestureStyle = new GestureStyle({
1139    onClick: () => {
1140      promptAction.showToast({ message: 'clickGestureAttr object trigger click event' })
1141      this.backgroundColor1 = Color.Yellow
1142    }
1143  })
1144  gestureStyleAttr: GestureStyle = new GestureStyle({
1145    onClick: () => {
1146      promptAction.showToast({ message: 'gestureStyleAttr object trigger click event' })
1147      this.backgroundColor1 = Color.Green
1148    },
1149    onLongPress: () => {
1150      promptAction.showToast({ message: 'gestureStyleAttr object trigger long press event' })
1151      this.backgroundColor1 = Color.Orange
1152    }
1153  });
1154  // 创建事件的对象mutableStyledString3
1155  mutableStyledString3: MutableStyledString = new MutableStyledString("hello world", [{
1156    start: 0,
1157    length: 5,
1158    styledKey: StyledStringKey.GESTURE,
1159    styledValue: this.clickGestureAttr
1160  },
1161    {
1162      start: 0,
1163      length: 5,
1164      styledKey: StyledStringKey.FONT,
1165      styledValue: this.fontStyleAttr1
1166    },
1167    {
1168      start: 6,
1169      length: 5,
1170      styledKey: StyledStringKey.GESTURE,
1171      styledValue: this.gestureStyleAttr
1172    },
1173    {
1174      start: 6,
1175      length: 5,
1176      styledKey: StyledStringKey.FONT,
1177      styledValue: new TextStyle({ fontColor: Color.Pink })
1178    }]);
1179  @State fontColor1: ResourceColor = Color.Red;
1180  @State backgroundColor1: ResourceColor | undefined = undefined;
1181  controller3: TextController = new TextController();
1182
1183  async onPageShow() {
1184    this.controller3.setStyledString(this.mutableStyledString3)
1185  }
1186
1187  build() {
1188    Column() {
1189      Scroll(this.scroll) {
1190        Column({ space: 30 }) {
1191          Button("响应属性字符串事件改变背景色").backgroundColor(this.backgroundColor1).width('80%')
1192          // 包含事件的属性字符串
1193          Text(undefined, { controller: this.controller3 }).fontSize(30)
1194            .copyOption(CopyOptions.InApp)
1195            .draggable(true)
1196            .clip(true)
1197        }.width('100%')
1198      }
1199      .expandSafeArea([SafeAreaType.KEYBOARD])
1200      .scrollable(ScrollDirection.Vertical)
1201      .scrollBar(BarState.On)
1202      .scrollBarColor(Color.Gray)
1203      .scrollBarWidth(10)
1204      .edgeEffect(EdgeEffect.None)
1205    }
1206    .width('100%')
1207  }
1208}
1209```
1210
1211![](figures/styledstring_2.png)
1212
1213### 示例3
1214
1215属性字符串支持文本样式接口示例
1216
1217```ts
1218// xxx.ets
1219import { LengthMetrics, LengthUnit } from '@kit.ArkUI'
1220
1221@Entry
1222@Component
1223struct styled_string_demo3 {
1224  fontStyleAttr1: TextStyle = new TextStyle({ fontColor: Color.Blue });
1225  fontStyleAttr2: StyledStringValue = new TextStyle({
1226    fontColor: Color.Orange,
1227    fontSize: LengthMetrics.vp(20),
1228    fontWeight: FontWeight.Bolder,
1229    fontStyle: FontStyle.Italic,
1230    fontFamily: "Arial"
1231  });
1232  fontStyleAttr3: StyledStringValue = new TextStyle({
1233    fontColor: Color.Orange,
1234    fontSize: LengthMetrics.vp(20),
1235    fontWeight: FontWeight.Lighter,
1236    fontStyle: FontStyle.Italic,
1237    fontFamily: "Arial"
1238  });
1239  // 创建多重TextStyle样式的对象mutableStyledString1
1240  mutableStyledString1: MutableStyledString = new MutableStyledString("运动45分钟", [{
1241    start: 0,
1242    length: 2,
1243    styledKey: StyledStringKey.FONT,
1244    styledValue: this.fontStyleAttr3
1245  }, {
1246    start: 2,
1247    length: 2,
1248    styledKey: StyledStringKey.FONT,
1249    styledValue: this.fontStyleAttr2
1250  }
1251  ]);
1252  // 创建有多种样式组合对象mutableStyledString2
1253  mutableStyledString2: MutableStyledString = new MutableStyledString("test hello world", [{
1254    start: 0,
1255    length: 5,
1256    styledKey: StyledStringKey.FONT,
1257    styledValue: this.fontStyleAttr1
1258  }, {
1259    start: 0,
1260    length: 5,
1261    styledKey: StyledStringKey.DECORATION,
1262    styledValue: new DecorationStyle({ type: TextDecorationType.LineThrough, color: Color.Blue })
1263  }, {
1264    start: 0,
1265    length: 5,
1266    styledKey: StyledStringKey.TEXT_SHADOW,
1267    styledValue: new TextShadowStyle({
1268      radius: 5,
1269      type: ShadowType.COLOR,
1270      color: Color.Yellow,
1271      offsetX: 10,
1272      offsetY: -10
1273    })
1274  }, {
1275    start: 0,
1276    length: 5,
1277    styledKey: StyledStringKey.BASELINE_OFFSET,
1278    styledValue: new BaselineOffsetStyle(LengthMetrics.px(20))
1279  }, {
1280    start: 0,
1281    length: 5,
1282    styledKey: StyledStringKey.LETTER_SPACING,
1283    styledValue: new LetterSpacingStyle(new LengthMetrics(10, LengthUnit.VP))
1284  }, {
1285    start: 6,
1286    length: 5,
1287    styledKey: StyledStringKey.BASELINE_OFFSET,
1288    styledValue: new BaselineOffsetStyle(LengthMetrics.fp(10))
1289  }
1290  ]);
1291  @State fontColor1: ResourceColor = Color.Red;
1292  controller: TextController = new TextController();
1293  options: TextOptions = { controller: this.controller };
1294  controller2: TextController = new TextController();
1295  spanStyle1: SpanStyle = {
1296    start: 0,
1297    length: 5,
1298    styledKey: StyledStringKey.FONT,
1299    styledValue: new TextStyle({ fontColor: Color.Pink })
1300  };
1301
1302  async onPageShow() {
1303    this.controller.setStyledString(this.mutableStyledString1)
1304    this.controller2.setStyledString(this.mutableStyledString2)
1305  }
1306
1307  build() {
1308    Column() {
1309      Column({ space: 10 }) {
1310        // 显示配了字体各种样式的属性字符串,Text组件亦配置冲突部分生效属性字符串配置,未冲突区间生效Text组件属性设置值
1311        Text(undefined, this.options)
1312          .fontColor(this.fontColor1)
1313          .font({ size: 20, weight: 500, style: FontStyle.Normal })
1314        // 显示配置了文本阴影、划线、字符间距、基线偏移量的属性字符串,Text组件亦配置生效属性字符串配置
1315        Text(undefined, { controller: this.controller2 })
1316          .fontSize(30)
1317          .copyOption(CopyOptions.InApp)
1318          .draggable(true)
1319          .decoration({ type: TextDecorationType.Overline, color: Color.Pink })
1320          .textShadow({
1321            radius: 10,
1322            type: ShadowType.COLOR,
1323            color: Color.Green,
1324            offsetX: -10,
1325            offsetY: 10
1326          })
1327        Button('查询字体样式')
1328          .onClick(() => {
1329            let styles = this.mutableStyledString1.getStyles(0, this.mutableStyledString1.length)
1330            if (styles.length !== 0) {
1331              for (let i = 0; i < styles.length; i++) {
1332                console.info('mutableStyledString1 style object start:' + styles[i].start)
1333                console.info('mutableStyledString1 style object length:' + styles[i].length)
1334                console.info('mutableStyledString1 style object key:' + styles[i].styledKey)
1335                if (styles[i].styledKey === 0) {
1336                  let fontAttr = styles[i].styledValue as TextStyle;
1337                  console.info('mutableStyledString1 fontColor:' + fontAttr.fontColor)
1338                  console.info('mutableStyledString1 fontSize:' + fontAttr.fontSize)
1339                  console.info('mutableStyledString1 fontWeight:' + fontAttr.fontWeight)
1340                  console.info('mutableStyledString1 fontStyle:' + fontAttr.fontStyle)
1341                  console.info('mutableStyledString1 fontStyle:' + fontAttr.fontFamily)
1342                }
1343              }
1344            }
1345          })
1346          .margin({ top: 10 })
1347        Button('查询其他文本样式')
1348          .onClick(() => {
1349            let styles = this.mutableStyledString2.getStyles(0, this.mutableStyledString2.length)
1350            if (styles.length !== 0) {
1351              for (let i = 0; i < styles.length; i++) {
1352                console.info('mutableStyledString2 style object start:' + styles[i].start)
1353                console.info('mutableStyledString2 style object length:' + styles[i].length)
1354                console.info('mutableStyledString2 style object key:' + styles[i].styledKey)
1355                if (styles[i].styledKey === 1) {
1356                  let decoAttr = styles[i].styledValue as DecorationStyle;
1357                  console.info('mutableStyledString2 decoration type:' + decoAttr.type)
1358                  console.info('mutableStyledString2 decoration color:' + decoAttr.color)
1359                }
1360                if (styles[i].styledKey === 2) {
1361                  let baselineAttr = styles[i].styledValue as BaselineOffsetStyle;
1362                  console.info('mutableStyledString2 baselineOffset:' + baselineAttr.baselineOffset)
1363                }
1364                if (styles[i].styledKey === 3) {
1365                  let letterAttr = styles[i].styledValue as LetterSpacingStyle;
1366                  console.info('mutableStyledString2 letterSpacing:' + letterAttr.letterSpacing)
1367                }
1368                if (styles[i].styledKey === 4) {
1369                  let textShadowAttr = styles[i].styledValue as TextShadowStyle;
1370                  let shadowValues = textShadowAttr.textShadow;
1371                  if (shadowValues.length > 0) {
1372                    for (let j = 0; j < shadowValues.length; j++) {
1373                      console.info('mutableStyledString2 textShadow type:' + shadowValues[j].type);
1374                      console.info('mutableStyledString2 textShadow radius:' + shadowValues[j].radius);
1375                      console.info('mutableStyledString2 textShadow color:' + shadowValues[j].color);
1376                      console.info('mutableStyledString2 textShadow offsetX:' + shadowValues[j].offsetX);
1377                      console.info('mutableStyledString2 textShadow offsetY:' + shadowValues[j].offsetY);
1378                    }
1379                  }
1380                }
1381              }
1382            }
1383          })
1384          .margin({ top: 10 })
1385        Button('更新mutableStyledString1样式')
1386          .onClick(() => {
1387            this.mutableStyledString1.setStyle(this.spanStyle1)
1388            this.controller.setStyledString(this.mutableStyledString1)
1389          })
1390          .margin({ top: 10 })
1391      }.width('100%')
1392    }
1393    .width('100%')
1394  }
1395}
1396```
1397![](figures/styledstring_3.png)
1398
1399### 示例4
1400
1401属性字符串图片接口使用示例
1402
1403```ts
1404// xxx.ets
1405import { image } from '@kit.ImageKit'
1406import { LengthMetrics } from '@kit.ArkUI'
1407
1408@Entry
1409@Component
1410struct styled_string_demo4 {
1411  @State message: string = 'Hello World'
1412  imagePixelMap: image.PixelMap | undefined = undefined
1413  @State imagePixelMap3: image.PixelMap | undefined = undefined
1414  mutableStr: MutableStyledString = new MutableStyledString('123');
1415  controller: TextController = new TextController();
1416  mutableStr2: MutableStyledString = new MutableStyledString('This is set decoration line style to the mutableStr2', [{
1417    start: 0,
1418    length: 15,
1419    styledKey: StyledStringKey.DECORATION,
1420    styledValue: new DecorationStyle({
1421      type: TextDecorationType.Overline,
1422      color: Color.Orange,
1423      style: TextDecorationStyle.DOUBLE
1424    })
1425  }])
1426
1427  async aboutToAppear() {
1428    console.info("aboutToAppear initial imagePixelMap")
1429    this.imagePixelMap = await this.getPixmapFromMedia($r('app.media.icon'))
1430  }
1431
1432  private async getPixmapFromMedia(resource: Resource) {
1433    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
1434      bundleName: resource.bundleName,
1435      moduleName: resource.moduleName,
1436      id: resource.id
1437    })
1438    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
1439    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
1440      desiredPixelFormat: image.PixelMapFormat.RGBA_8888
1441    })
1442    await imageSource.release()
1443    return createPixelMap
1444  }
1445
1446  build() {
1447    Row() {
1448      Column({ space: 5 }) {
1449        Text(undefined, { controller: this.controller })
1450          .copyOption(CopyOptions.InApp)
1451          .draggable(true)
1452          .fontSize(30)
1453
1454        Button('设置图片')
1455          .onClick(() => {
1456            if (this.imagePixelMap !== undefined) {
1457              this.mutableStr = new MutableStyledString(new ImageAttachment({
1458                value: this.imagePixelMap,
1459                size: { width: 50, height: 50 },
1460                layoutStyle: { borderRadius: LengthMetrics.vp(10) },
1461                verticalAlign: ImageSpanAlignment.BASELINE,
1462                objectFit: ImageFit.Contain
1463              }))
1464              this.controller.setStyledString(this.mutableStr)
1465            }
1466          })
1467
1468        Button('Image之Append')
1469          .onClick(() => {
1470            let str = new StyledString('123')
1471            this.mutableStr.appendStyledString(str)
1472            this.controller.setStyledString(this.mutableStr)
1473          })
1474
1475        Button('Image之Insert 前')
1476          .onClick(() => {
1477            this.mutableStr.insertString(0, '123')
1478            this.controller.setStyledString(this.mutableStr)
1479          })
1480
1481        Button('Image之Insert 后')
1482          .onClick(() => {
1483            this.mutableStr.insertString(1, '123')
1484            this.controller.setStyledString(this.mutableStr)
1485          })
1486
1487        Button('Image之replace')
1488          .onClick(() => {
1489            this.mutableStr.replaceString(2, 5, "789")
1490            this.controller.setStyledString(this.mutableStr)
1491          })
1492
1493        Button('Image之Get')
1494          .onClick(() => {
1495            let imageArray = this.mutableStr.getStyles(0, 1, StyledStringKey.IMAGE)
1496            for (let i = 0; i < imageArray.length; ++i) {
1497              console.info('mutableStr start ' + imageArray[i].start + ' length ' + imageArray[i].length + ' type ' + imageArray[i].styledKey)
1498              if (imageArray[i].styledKey === 300) {
1499                let attachment = imageArray[i].styledValue as ImageAttachment
1500                this.imagePixelMap3 = attachment.value
1501                console.info('mutableStr value ' + JSON.stringify(attachment.value))
1502                if (attachment.size !== undefined) {
1503                  console.info('mutableStr size width ' + attachment.size.width + ' height ' + attachment.size.height)
1504                }
1505                console.info('mutableStr vertical ' + attachment.verticalAlign)
1506                console.info('mutableStr fit ' + attachment.objectFit)
1507                if (attachment.layoutStyle !== undefined) {
1508                  let radius = attachment.layoutStyle.borderRadius as BorderRadiuses
1509                  console.info('mutableStr radius ' + JSON.stringify(radius))
1510                }
1511              }
1512
1513            }
1514          })
1515
1516        Image(this.imagePixelMap3).width(50).height(50)
1517
1518      }
1519      .width('100%')
1520    }
1521    .height('100%')
1522  }
1523}
1524```
1525
1526![](figures/styledstring_4.png)
1527
1528### 示例5
1529
1530属性字符串LineHeightStyle、ParagraphStyle使用示例
1531
1532```ts
1533import { LengthMetrics } from '@kit.ArkUI'
1534const canvasWidth = 1000
1535const canvasHeight = 100
1536class LeadingMarginCreator {
1537  private settings: RenderingContextSettings = new RenderingContextSettings(true)
1538  private offscreenCanvas: OffscreenCanvas = new OffscreenCanvas(canvasWidth, canvasHeight)
1539  private offContext: OffscreenCanvasRenderingContext2D = this.offscreenCanvas.getContext("2d", this.settings)
1540  public static instance: LeadingMarginCreator = new LeadingMarginCreator()
1541
1542  public genSquareMark(fontSize: number): PixelMap {
1543    this.offContext = this.offscreenCanvas.getContext("2d", this.settings)
1544    this.clearCanvas()
1545    const coordinate = fontSize * (1 - 1 / 1.5) / 2
1546    const sideLength = fontSize / 1.5
1547    this.offContext.fillRect(coordinate, coordinate, sideLength, sideLength)
1548    return this.offContext.getPixelMap(0, 0, fontSize, fontSize)
1549  }
1550
1551  private clearCanvas() {
1552    this.offContext.clearRect(0, 0, canvasWidth, canvasHeight)
1553  }
1554}
1555@Entry
1556@Component
1557struct Index {
1558  private leadingMarkCreatorInstance = LeadingMarginCreator.instance
1559  leadingMarginPlaceholder1: LeadingMarginPlaceholder = {
1560    pixelMap: this.leadingMarkCreatorInstance.genSquareMark(24),
1561    size:[15, 15]
1562  }
1563  titleParagraphStyleAttr: ParagraphStyle = new ParagraphStyle({ textAlign: TextAlign.Center });
1564  //第一段落首行缩进15vp
1565  paragraphStyleAttr1: ParagraphStyle = new ParagraphStyle({ textIndent: LengthMetrics.vp(15) });
1566  //第二段落缩进15vp且首行有placeholder占位显示
1567  paragraphStyleAttr2: ParagraphStyle = new ParagraphStyle({ textAlign: TextAlign.Start, leadingMargin:  this.leadingMarginPlaceholder1 });
1568  //第三段落不设置缩进配置最大行数及超长显示方式
1569  paragraphStyleAttr3: ParagraphStyle = new ParagraphStyle({ textAlign: TextAlign.End, maxLines: 1, wordBreak: WordBreak.BREAK_ALL, overflow: TextOverflow.Ellipsis});
1570  //行高样式对象
1571  lineHeightStyle1: LineHeightStyle= new LineHeightStyle(new LengthMetrics(24));
1572  //创建含段落样式的对象paragraphStyledString1
1573  paragraphStyledString1: StyledString = new StyledString("段落标题\n正文第一段落开始0123456789正文第一段落结束\n正文第二段落开始hello world正文第二段落结束\n正文第三段落ABCDEFGHIJKLMNOPQRSTUVWXYZ。", [
1574    {
1575      start: 0,
1576      length: 4,
1577      styledKey: StyledStringKey.PARAGRAPH_STYLE,
1578      styledValue: this.titleParagraphStyleAttr
1579    },
1580    {
1581      start: 0,
1582      length: 4,
1583      styledKey: StyledStringKey.LINE_HEIGHT,
1584      styledValue: new LineHeightStyle(new LengthMetrics(50))
1585    },{
1586    start: 0,
1587    length: 4,
1588    styledKey: StyledStringKey.FONT,
1589    styledValue: new TextStyle({ fontSize: LengthMetrics.vp(24), fontWeight: FontWeight.Bolder })
1590  },
1591    {
1592      start: 5,
1593      length: 3,
1594      styledKey: StyledStringKey.PARAGRAPH_STYLE,
1595      styledValue: this.paragraphStyleAttr1
1596    },
1597    {
1598      start: 5,
1599      length: 20,
1600      styledKey: StyledStringKey.LINE_HEIGHT,
1601      styledValue: this.lineHeightStyle1
1602    },
1603    {
1604      start: 32,
1605      length: 5,
1606      styledKey: StyledStringKey.PARAGRAPH_STYLE,
1607      styledValue: this.paragraphStyleAttr2
1608    },
1609    {
1610      start: 32,
1611      length: 20,
1612      styledKey: StyledStringKey.LINE_HEIGHT,
1613      styledValue: this.lineHeightStyle1
1614    },
1615    {
1616      start: 60,
1617      length: 5,
1618      styledKey: StyledStringKey.PARAGRAPH_STYLE,
1619      styledValue: this.paragraphStyleAttr3
1620    },
1621    {
1622      start: 60,
1623      length: 5,
1624      styledKey: StyledStringKey.LINE_HEIGHT,
1625      styledValue: this.lineHeightStyle1
1626    }
1627  ]);
1628  controller: TextController = new TextController();
1629  async onPageShow() {
1630    this.controller.setStyledString(this.paragraphStyledString1)
1631  }
1632
1633  build() {
1634    Row() {
1635      Column( { space : 5 }) {
1636        Text(undefined, { controller: this.controller })
1637          .width(240)
1638          .borderWidth(1)
1639          .copyOption(CopyOptions.InApp)
1640          .draggable(true)
1641
1642        //查询段落样式
1643        Text()
1644          .onClick(() => {
1645            let styles = this.paragraphStyledString1.getStyles(0, this.paragraphStyledString1.length)
1646            if (styles.length !== 0) {
1647              for (let i = 0; i < styles.length; i++) {
1648                console.info('paragraphStyledString1 style object start:' + styles[i].start)
1649                console.info('paragraphStyledString1 style object length:' + styles[i].length)
1650                console.info('paragraphStyledString1 style object key:' + styles[i].styledKey)
1651                if (styles[i].styledKey === 200) {
1652                  let paraAttr = styles[i].styledValue as ParagraphStyle;
1653                  console.info('paragraphStyledString1 textAlign:' + paraAttr.textAlign)
1654                  console.info('paragraphStyledString1 textIndent:' + paraAttr.textIndent)
1655                  console.info('paragraphStyledString1 maxLines:' + paraAttr.maxLines)
1656                  console.info('paragraphStyledString1 wordBreak:' + paraAttr.wordBreak)
1657                  console.info('paragraphStyledString1 leadingMargin:' + paraAttr.leadingMargin)
1658                  console.info('paragraphStyledString1 overflow:' + paraAttr.overflow)
1659                }
1660              }
1661            }
1662          })
1663          .margin({ top: 10 })
1664      }
1665      .width('100%')
1666    }
1667    .height('100%')
1668  }
1669}
1670```
1671
1672![](figures/styledstring_5.png)
1673
1674### 示例6
1675
1676属性字符串自定义绘制Span使用示例
1677
1678```ts
1679// xxx.ets
1680import { drawing } from '@kit.ArkGraphics2D'
1681import { LengthMetrics } from '@kit.ArkUI'
1682
1683class MyCustomSpan extends CustomSpan {
1684  constructor(word: string, width: number, height: number) {
1685    super();
1686    this.word = word;
1687    this.width = width;
1688    this.height = height;
1689  }
1690
1691  onMeasure(measureInfo: CustomSpanMeasureInfo): CustomSpanMetrics {
1692    return { width: this.width, height: this.height };
1693  }
1694
1695  onDraw(context: DrawContext, options: CustomSpanDrawInfo) {
1696    let canvas = context.canvas;
1697
1698    const brush = new drawing.Brush();
1699    brush.setColor({
1700      alpha: 255,
1701      red: 0,
1702      green: 74,
1703      blue: 175
1704    });
1705    const font = new drawing.Font();
1706    font.setSize(25);
1707    const textBlob = drawing.TextBlob.makeFromString(this.word, font, drawing.TextEncoding.TEXT_ENCODING_UTF8);
1708    canvas.attachBrush(brush);
1709    canvas.drawRect({
1710      left: options.x + 10,
1711      right: options.x + vp2px(this.width) - 10,
1712      top: options.lineTop + 10,
1713      bottom: options.lineBottom - 10
1714    });
1715
1716    brush.setColor({
1717      alpha: 255,
1718      red: 23,
1719      green: 169,
1720      blue: 141
1721    });
1722    canvas.attachBrush(brush);
1723    canvas.drawTextBlob(textBlob, options.x + 20, options.lineBottom - 15);
1724    canvas.detachBrush();
1725  }
1726
1727  setWord(word: string) {
1728    this.word = word;
1729  }
1730
1731  width: number = 160;
1732  word: string = "drawing";
1733  height: number = 10;
1734}
1735
1736@Entry
1737@Component
1738struct styled_string_demo6 {
1739  customSpan1: MyCustomSpan = new MyCustomSpan("Hello", 80, 10);
1740  customSpan2: MyCustomSpan = new MyCustomSpan("World", 80, 40);
1741  style: MutableStyledString = new MutableStyledString(this.customSpan1);
1742  textStyle: MutableStyledString = new MutableStyledString("123");
1743  textController: TextController = new TextController();
1744  isPageShow: boolean = true;
1745
1746  async onPageShow() {
1747    if (!this.isPageShow) {
1748      return
1749    }
1750    this.isPageShow = false;
1751
1752    this.style.appendStyledString(new MutableStyledString("文本绘制 示例代码 CustomSpan", [
1753      {
1754        start: 0,
1755        length: 5,
1756        styledKey: StyledStringKey.FONT,
1757        styledValue: new TextStyle({ fontColor: Color.Pink })
1758      }, {
1759      start: 5,
1760      length: 5,
1761      styledKey: StyledStringKey.FONT,
1762      styledValue: new TextStyle({ fontColor: Color.Orange, fontStyle: FontStyle.Italic })
1763    }, {
1764      start: 10,
1765      length: 500,
1766      styledKey: StyledStringKey.FONT,
1767      styledValue: new TextStyle({ fontColor: Color.Green, fontWeight: FontWeight.Bold })
1768    }
1769    ]))
1770    this.style.appendStyledString(new StyledString(this.customSpan2))
1771    this.style.appendStyledString(new StyledString("自定义绘制", [{
1772      start: 0,
1773      length: 5,
1774      styledKey: StyledStringKey.FONT,
1775      styledValue: new TextStyle({ fontColor: Color.Green, fontSize: LengthMetrics.px(50) })
1776    }]))
1777    this.textController.setStyledString(this.style)
1778  }
1779
1780  build() {
1781    Row() {
1782      Column() {
1783        Text(undefined, { controller: this.textController })
1784          .copyOption(CopyOptions.InApp)
1785          .fontSize(30)
1786
1787        Button("invalidate").onClick(() => {
1788          this.customSpan1.setWord("你好")
1789          this.customSpan1.invalidate()
1790        })
1791      }
1792      .width('100%')
1793    }
1794    .height('100%')
1795  }
1796}
1797```
1798
1799![](figures/styledstring_6.gif)
1800
1801### 示例7
1802
1803属性字符串UserDataSpan使用示例
1804
1805```ts
1806// xxx.ets
1807class MyUserDateSpan extends UserDataSpan {
1808  constructor(name: string, age: number) {
1809    super()
1810    this.name = name
1811    this.age = age
1812  }
1813
1814  name: string
1815  age: number
1816}
1817
1818@Entry
1819@Component
1820struct styled_string_demo7 {
1821  @State name: string = "world"
1822  @State age: number = 10
1823  controller: TextController = new TextController()
1824  styleString: MutableStyledString = new MutableStyledString("hello world", [{
1825    start: 0,
1826    length: 11,
1827    styledKey: StyledStringKey.USER_DATA,
1828    styledValue: new MyUserDateSpan("hello", 21)
1829  }])
1830
1831  onPageShow(): void {
1832    this.controller.setStyledString(this.styleString)
1833  }
1834
1835  build() {
1836    Column() {
1837      Text(undefined, { controller: this.controller })
1838      Button("get user data").onClick(() => {
1839        let arr = this.styleString.getStyles(0, this.styleString.length)
1840        let userDataSpan = arr[0].styledValue as MyUserDateSpan
1841        this.name = userDataSpan.name
1842        this.age = userDataSpan.age
1843      })
1844      Text("name:" + this.name + "  age: " + this.age)
1845    }.width('100%').height(250).padding({ left: 35, right: 35, top: 35 })
1846  }
1847}
1848```
1849
1850![](figures/styledstring_7.gif)
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862