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