• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Text
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @xiangyuan6-->
5<!--Designer: @pssea-->
6<!--Tester: @jiaoaozihao-->
7<!--Adviser: @HelloCrease-->
8
9显示一段文本的组件。
10
11>  **说明:**
12>
13>  该组件从API version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
14>
15>  <!--RP3--><!--RP3End-->
16
17
18## 子组件
19
20可以包含[Span](ts-basic-components-span.md)、[ImageSpan](ts-basic-components-imagespan.md)、[SymbolSpan](ts-basic-components-symbolSpan.md)和[ContainerSpan](ts-basic-components-containerspan.md)子组件。
21
22>  **说明:**
23>
24>  使用[子组件](#子组件)实现[图文混排](../../../ui/arkts-text-image-layout.md)场景。
25
26## 接口
27
28Text(content?: string | Resource , value?: TextOptions)
29
30**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
31
32**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
33
34**系统能力:** SystemCapability.ArkUI.ArkUI.Full
35
36**参数:**
37
38| 参数名 | 类型 | 必填 | 说明 |
39| -------- | -------- | -------- | -------- |
40| content | string \| [Resource](ts-types.md#resource) | 否 | 文本内容。当不包含子组件[Span](ts-basic-components-span.md)和未设置[属性字符串](ts-universal-styled-string.md)时该参数生效。<br/>默认值:' '<br/>**说明:** <br/>显示内容的优先级:属性字符串>Span>Text的文本内容。 |
41| value<sup>11+</sup> | [TextOptions](#textoptions11) | 否 | 文本组件初始化选项。|
42
43## 属性
44
45除支持[通用属性](ts-component-general-attributes.md),还支持以下属性:
46
47### textAlign
48
49textAlign(value: TextAlign)
50
51设置文本段落在水平方向的对齐方式。
52
53文本段落宽度占满Text组件宽度。
54
55可通过[align](ts-universal-attributes-location.md#align)属性控制文本段落在垂直方向上的位置,此组件中不可通过align属性控制文本段落在水平方向上的位置,具体效果如下:
56
57- Alignment.TopStartAlignment.TopAlignment.TopEnd:内容顶部对齐。
58
59- Alignment.StartAlignment.CenterAlignment.End:内容垂直居中。
60
61- Alignment.BottomStartAlignment.BottomAlignment.BottomEnd:内容底部对齐。
62
63当textAlign属性设置为TextAlign.JUSTIFY时,需要根据文本内容设置[wordBreak](#wordbreak11)属性,且最后一行文本水平对齐首部,不参与两端对齐。
64
65**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
66
67**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
68
69**系统能力:** SystemCapability.ArkUI.ArkUI.Full
70
71**参数:**
72
73| 参数名 | 类型                                        | 必填 | 说明                                                       |
74| ------ | ------------------------------------------- | ---- | ---------------------------------------------------------- |
75| value  | [TextAlign](ts-appendix-enums.md#textalign) | 是   | 文本段落在水平方向的对齐方式。<br/>默认值:TextAlign.Start<br/>Wearable设备上默认值为:TextAlign.Center |
76
77>  **说明:**
78>
79>  textAlign只能调整文本整体的布局,不影响字符的显示顺序。若需要调整字符的显示顺序,请参考[镜像状态字符对齐](../../../ui/arkts-internationalization.md#镜像状态字符对齐)。
80
81### textVerticalAlign<sup>20+</sup>
82
83textVerticalAlign(textVerticalAlign: Optional\<TextVerticalAlign>)
84
85设置文本段落在垂直方向的对齐方式。
86
87与[halfLeading](#halfleading12)同时配置时,halfLeading不生效。
88
89**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
90
91**系统能力:** SystemCapability.ArkUI.ArkUI.Full
92
93**参数:**
94
95| 参数名 | 类型                                        | 必填 | 说明                                                       |
96| ------ | ------------------------------------------- | ---- | ---------------------------------------------------------- |
97| textVerticalAlign  | [Optional](ts-universal-attributes-custom-property.md#optionalt12)\<[TextVerticalAlign](ts-text-common.md#textverticalalign20)> | 是   | 文本段落在垂直方向的对齐方式。<br/>默认值:TextVerticalAlign.BASELINE |
98
99### textOverflow
100
101textOverflow(options: TextOverflowOptions)
102
103设置文本超长时的显示方式。
104
105当[TextOverflowOptions](#textoverflowoptions18对象说明)设置为TextOverflow.NoneTextOverflow.ClipTextOverflow.Ellipsis时:
106
107- 设置为TextOverflow.NoneTextOverflow.Clip,文本超长时按最大行截断显示。
108
109- 设置为TextOverflow.Ellipsis,文本超长时显示不下的文本用省略号代替。
110
111- 需配合[maxLines](#maxlines)使用,单独设置不生效。
112
113- 断行规则参考[wordBreak](#wordbreak11)。默认情况下参考WordBreak.BREAK_WORD的截断方式,文本截断按字进行。例如,英文以单词为最小单位进行截断。若需要以字母为单位进行截断,可设置wordBreak属性为WordBreak.BREAK_ALL114
115- 折行规则参考[lineBreakStrategy](#linebreakstrategy12)。该属性在[wordBreak](#wordbreak11)不等于WordBreak.BREAK_ALL的时候生效,不支持连词符。
116
117- 从API version 11开始,建议优先组合[textOverflow](#textoverflow)和[wordBreak](#wordbreak11)属性来设置截断方式,具体详见[示例4设置文本断行及折行](#示例4设置文本断行及折行)<!--RP1--><!--RP1End-->。
118
119当TextOverflowOptions设置为TextOverflow.MARQUEE时:
120
121- 文本在一行内滚动显示。
122
123- 设置[maxLines](#maxlines)及[copyOption](#copyoption9)属性均不生效。
124
125- Text组件[clip](ts-universal-attributes-sharp-clipping.md#clip12)属性默认为true。
126
127- 属性字符串的[CustomSpan](ts-universal-styled-string.md#customspan)不支持跑马灯模式。
128
129- [textAlign](#textalign)属性的生效规则:当文本不可滚动时,textAlign属性生效;当文本可滚动时,textAlign属性不生效。
130
131- 从API version 12开始,当TextOverflowOptions设置为TextOverflow.MARQUEE时,支持ImageSpan组件,文本和图片可在一行内滚动显示。
132
133**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
134
135**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
136
137**系统能力:** SystemCapability.ArkUI.ArkUI.Full
138
139**参数:**
140
141| 参数名 | 类型                                                         | 必填 | 说明                                                         |
142| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
143| options | [TextOverflowOptions](#textoverflowoptions18对象说明) | 是   | 文本超长显示方式对象 |
144
145### maxLines
146
147maxLines(value: number)
148
149设置文本的最大行数。
150
151默认情况下,文本是自动折行的,如果指定此属性,则文本最多不会超过指定的行。如果有多余的文本,可以通过[textOverflow](#textoverflow)来指定截断方式。
152
153**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
154
155**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
156
157**系统能力:** SystemCapability.ArkUI.ArkUI.Full
158
159**参数:**
160
161| 参数名 | 类型   | 必填 | 说明             |
162| ------ | ------ | ---- | ---------------- |
163| value  | number | 是   | 文本的最大行数。<br/>**说明:** <br/>取值范围:[0, INT32_MAX]<br/>设置为0时,不显示文本内容。 |
164
165### lineHeight
166
167lineHeight(value: number | string | Resource)
168
169设置文本的文本行高。
170
171设置值不大于0时,不限制文本行高,自适应字体大小,number类型时单位为fp。string类型支持number类型取值的字符串形式,可以附带单位,例如"10"、"10fp"。
172
173**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
174
175**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
176
177**系统能力:** SystemCapability.ArkUI.ArkUI.Full
178
179**参数:**
180
181| 参数名 | 类型                                                         | 必填 | 说明             |
182| ------ | ------------------------------------------------------------ | ---- | ---------------- |
183| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 文本的文本行高。 |
184
185>  **说明:**
186>
187>  特殊字符字体高度远超出同行的其他字符高度时,文本框出现截断、遮挡、内容相对位置发生变化等不符合预期的显示异常,需要开发者调整组件高度、行高等属性,修改对应的页面布局。
188
189### decoration
190
191decoration(value: DecorationStyleInterface)
192
193设置文本装饰线样式及其颜色。
194
195**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
196
197**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
198
199**系统能力:** SystemCapability.ArkUI.ArkUI.Full
200
201**参数:**
202
203| 参数名 | 类型                                                         | 必填 | 说明                                                         |
204| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
205| value  | [DecorationStyleInterface<sup>12+</sup>](ts-universal-styled-string.md#decorationstyleinterface) | 是   | 文本装饰线样式对象。<br/>默认值:<br/>{<br/>&nbsp;type:&nbsp;TextDecorationType.None,<br/>&nbsp;color:&nbsp;Color.Black,<br/>&nbsp;style:&nbsp;TextDecorationStyle.SOLID&nbsp;<br/>}<br/>**说明:** <br/>style参数不支持卡片能力。 |
206
207>  **说明:**
208>
209>  当文字的下边缘轮廓与装饰线位置相交时,会触发下划线避让规则,下划线将在这些字符处避让文字。常见“gjyqp”等英文字符。
210
211### baselineOffset
212
213baselineOffset(value: number | ResourceStr)
214
215设置文本基线的偏移量。
216
217设置该值为百分比时,按默认值显示。
218
219正数内容向上偏移,负数向下偏移。
220
221**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
222
223**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
224
225**系统能力:** SystemCapability.ArkUI.ArkUI.Full
226
227**参数:**
228
229| 参数名 | 类型                       | 必填 | 说明                             |
230| ------ | -------------------------- | ---- | -------------------------------- |
231| value  | number&nbsp;\|&nbsp;[ResourceStr](ts-types.md#resourcestr) | 是   | 文本基线的偏移量。<br/>默认值:0 <br>从API version 20开始,支持Resource类型。|
232
233### letterSpacing
234
235letterSpacing(value: number | ResourceStr)
236
237设置文本字符间距。
238
239设置该值为百分比时,按默认值显示。设置该值为0时,按默认值显示。string类型支持number类型取值的字符串形式,可以附带单位,例如"10"、"10fp"。
240
241当取值为负值时,文字会被压缩。负值过小时会将组件内容区大小压缩为0,导致内容无法显示。
242
243对每个字符生效,包括行尾字符。
244
245**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
246
247**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
248
249**系统能力:** SystemCapability.ArkUI.ArkUI.Full
250
251**参数:**
252
253| 参数名 | 类型                       | 必填 | 说明           |
254| ------ | -------------------------- | ---- | -------------- |
255| value  | number&nbsp;\|&nbsp;[ResourceStr](ts-types.md#resourcestr) | 是   | 文本字符间距。<br/>默认值:0<br/>单位:[fp](ts-pixel-units.md) <br>从API version 20开始,支持Resource类型。|
256
257### minFontSize
258
259minFontSize(value: number | string | Resource)
260
261设置文本最小显示字号。
262
263string类型支持number类型取值的字符串形式,可以附带单位,例如"10"、"10fp"。
264
265需配合[maxFontSize](#maxfontsize)以及[maxLines](#maxlines)或布局大小限制使用,单独设置不生效。
266
267自适应字号生效时,fontSize设置不生效。
268
269minFontSize小于或等于0时,自适应字号不生效,此时按照[fontSize](#fontsize)属性的值生效,未设置时按照其默认值生效。
270
271从API version 18开始,支持在子组件和属性字符串上生效,未设置字号的部分会自适应。
272
273**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
274
275**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
276
277**系统能力:** SystemCapability.ArkUI.ArkUI.Full
278
279**参数:**
280
281| 参数名 | 类型                                                         | 必填 | 说明               |
282| ------ | ------------------------------------------------------------ | ---- | ------------------ |
283| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 文本最小显示字号。<br/>单位:[fp](ts-pixel-units.md) |
284
285### maxFontSize
286
287maxFontSize(value: number | string | Resource)
288
289设置文本最大显示字号。
290
291string类型支持number类型取值的字符串形式,可以附带单位,例如"10"、"10fp"。
292
293需配合[minFontSize](#minfontsize)以及[maxLines](#maxlines)或布局大小限制使用,单独设置不生效。
294
295自适应字号生效时,fontSize设置不生效。
296
297maxFontSize小于等于0或者maxFontSize小于minFontSize时,自适应字号不生效,此时按照[fontSize](#fontsize)属性的值生效,未设置时按照其默认值生效。
298
299从API version 18开始支持在子组件和属性字符串上生效,未设置字号的部分会自适应。
300
301**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
302
303**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
304
305**系统能力:** SystemCapability.ArkUI.ArkUI.Full
306
307**参数:**
308
309| 参数名 | 类型                                                         | 必填 | 说明               |
310| ------ | ------------------------------------------------------------ | ---- | ------------------ |
311| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 文本最大显示字号。<br/>单位:[fp](ts-pixel-units.md) |
312
313### textCase
314
315textCase(value: TextCase)
316
317设置文本大小写。
318
319**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
320
321**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
322
323**系统能力:** SystemCapability.ArkUI.ArkUI.Full
324
325**参数:**
326
327| 参数名 | 类型                                      | 必填 | 说明                                      |
328| ------ | ----------------------------------------- | ---- | ----------------------------------------- |
329| value  | [TextCase](ts-appendix-enums.md#textcase) | 是   | 文本大小写。<br />默认值:TextCase.Normal |
330
331### fontColor
332
333fontColor(value: ResourceColor)
334
335设置字体颜色。
336
337**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
338
339**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
340
341**系统能力:** SystemCapability.ArkUI.ArkUI.Full
342
343**参数:**
344
345| 参数名 | 类型                                       | 必填 | 说明       |
346| ------ | ------------------------------------------ | ---- | ---------- |
347| value  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 字体颜色。<br />默认值:'#e6182431'<br />Wearable设备上默认值为:'#c5ffffff' |
348
349### fontSize
350
351fontSize(value: number | string | Resource)
352
353设置字体大小。
354
355**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
356
357**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
358
359**系统能力:** SystemCapability.ArkUI.ArkUI.Full
360
361**参数:**
362
363| 参数名 | 类型                                                         | 必填 | 说明                                                         |
364| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
365| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 字体大小。fontSize为number类型时,使用fp单位。不支持设置百分比字符串。<br />默认值:16fp<br />Wearable设备上默认值为:15fp |
366
367### fontStyle
368
369fontStyle(value: FontStyle)
370
371设置字体样式。
372
373**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
374
375**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
376
377**系统能力:** SystemCapability.ArkUI.ArkUI.Full
378
379**参数:**
380
381| 参数名 | 类型                                        | 必填 | 说明                                    |
382| ------ | ------------------------------------------- | ---- | --------------------------------------- |
383| value  | [FontStyle](ts-appendix-enums.md#fontstyle) | 是   | 字体样式。<br/>默认值:FontStyle.Normal |
384
385### fontWeight
386
387fontWeight(value: number | FontWeight | ResourceStr)
388
389设置文本的字体粗细,设置过大可能会在不同字体下有截断。
390
391**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
392
393**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
394
395**系统能力:** SystemCapability.ArkUI.ArkUI.Full
396
397**参数:**
398
399| 参数名 | 类型                                                         | 必填 | 说明                                                         |
400| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
401| value  | number&nbsp;\|&nbsp;[FontWeight](ts-appendix-enums.md#fontweight)&nbsp;\|&nbsp;[ResourceStr](ts-types.md#resourcestr) | 是   | 文本的字体粗细,number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。<br/>默认值:FontWeight.Normal<br/>Wearable设备上默认值为:FontWeight.Regular <br>从API version 20开始,支持Resource类型。|
402
403### fontFamily
404
405fontFamily(value: string | Resource)
406
407设置字体族。
408
409**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
410
411**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
412
413**系统能力:** SystemCapability.ArkUI.ArkUI.Full
414
415**参数:**
416
417| 参数名 | 类型                                                 | 必填 | 说明                                                         |
418| ------ | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
419| value  | string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 字体族。默认字体'HarmonyOS Sans'。<br>使用多个字体时,请用逗号','分隔,字体的优先级按顺序生效。例如:'Arial, HarmonyOS Sans'。<br>应用当前支持'HarmonyOS Sans'字体和注册自定义字体[loadFontSync](../../apis-arkgraphics2d/js-apis-graphics-text.md#loadfontsync)。<br>卡片当前仅支持'HarmonyOS Sans'字体。 |
420
421### copyOption<sup>9+</sup>
422
423copyOption(value: CopyOptions)
424
425设置组件是否支持文本可复制粘贴。
426
427从API version 20开始,当Text组件执行复制操作时,会将HTML格式的内容添加到剪贴板中。
428
429- 当Text组件包含子组件时,仅支持[Span](ts-basic-components-span.md)和[ImageSpan](ts-basic-components-imagespan.md)子组件向剪贴板中添加HTML格式的内容。
430
431- 设置Text组件的属性字符串时,请参考属性字符串[toHtml](ts-universal-styled-string.md#tohtml14)接口文档,以了解支持转换为HTML的范围。
432
433设置copyOption为CopyOptions.InApp或者CopyOptions.LocalDevice时:
434
435- 长按文本,会弹出文本选择菜单,可选中文本并进行复制、全选操作。
436
437- 默认情况下,长按选中文本可拖拽。若要取消此功能,可将 `draggable` 设置为 `false`。
438
439- 若需要支持Ctrl+C复制,需同时设置[textSelectable](#textselectable12)为TextSelectableMode.SELECTABLE_FOCUSABLE440
441此时Text会监听onClick事件,手势事件为非冒泡事件,若需要点击Text组件区域响应父组件的点击手势事件,建议在父组件上使用[parallelGesture](ts-gesture-settings.md#parallelgesture)绑定手势识别,也可参考[示例7设置文本识别](#示例7设置文本识别)。
442
443由于卡片没有长按事件,此场景下长按文本,不会弹出文本选择菜单。
444
445**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
446
447**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
448
449**系统能力:** SystemCapability.ArkUI.ArkUI.Full
450
451**参数:**
452
453| 参数名 | 类型                                             | 必填 | 说明                                                       |
454| ------ | ------------------------------------------------ | ---- | ---------------------------------------------------------- |
455| value  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 是   | 组件是否支持文本可复制粘贴。<br />默认值:CopyOptions.None |
456
457### contentTransition<sup>20+</sup>
458
459contentTransition(transition: Optional\<ContentTransition>)
460
461可以设置为数字翻牌动效[NumericTextTransition](../arkui-ts/ts-text-common.md#numerictexttransition20)。
462
463**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
464
465**系统能力:** SystemCapability.ArkUI.ArkUI.Full
466
467**参数:**
468
469| 参数名 | 类型                                             | 必填 | 说明                                                       |
470| ------ | ------------------------------------------------ | ---- | ---------------------------------------------------------- |
471| transition  | Optional\<[ContentTransition](../arkui-ts/ts-text-common.md#contenttransition20)> | 是   | 文本动效属性。 |
472
473### draggable<sup>9+</sup>
474
475draggable(value: boolean)
476
477设置选中文本拖拽效果。
478
479不能和[onDragStart](ts-universal-events-drag-drop.md#ondragstart)事件同时使用。
480
481当draggable设置为true时,需配合[CopyOptions](ts-appendix-enums.md#copyoptions9)使用,设置copyOptions为CopyOptions.InApp或者CopyOptions.LocalDevice,支持对选中文本的拖拽及复制到输入框。
482
483**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
484
485**系统能力:** SystemCapability.ArkUI.ArkUI.Full
486
487**参数:**
488
489| 参数名 | 类型    | 必填 | 说明                                 |
490| ------ | ------- | ---- | ------------------------------------ |
491| value  | boolean | 是   | 选中文本拖拽效果。<br/>true表示选中文本可拖拽,false表示不可拖拽。<br/>默认值:false |
492
493### font<sup>10+</sup>
494
495font(value: Font)
496
497设置文本样式。
498
499包括字体大小、字体粗细、字体族和字体风格。
500
501**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
502
503**系统能力:** SystemCapability.ArkUI.ArkUI.Full
504
505**参数:**
506
507| 参数名 | 类型    | 必填 | 说明       |
508| ------ | ------- | ---- | ---------- |
509| value  | [Font](ts-types.md#font) | 是   | 文本样式。 |
510
511### textShadow<sup>10+</sup>
512
513textShadow(value: ShadowOptions | Array&lt;ShadowOptions&gt;)
514
515设置文字阴影效果。
516
517不支持fill字段和智能取色模式。
518
519从API version 11开始,该接口支持以数组形式入参,实现多重文字阴影。
520
521**卡片能力:** 从API version 10开始,该接口支持在ArkTS卡片中使用。
522
523**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
524
525**系统能力:** SystemCapability.ArkUI.ArkUI.Full
526
527**参数:**
528
529| 参数名 | 类型                                                         | 必填 | 说明           |
530| ------ | ------------------------------------------------------------ | ---- | -------------- |
531| value  | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明)&nbsp;\|&nbsp;&nbsp;Array&lt;[ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明)&gt;<sup>11+</sup> | 是   | 文字阴影效果。 |
532
533### heightAdaptivePolicy<sup>10+</sup>
534
535heightAdaptivePolicy(value: TextHeightAdaptivePolicy)
536
537设置文本自适应布局调整字号的方式。
538
539规则如下:
540
541- MAX_LINES_FIRST模式:优先使用[maxLines](#maxlines)属性来调整文本高度。如果使用maxLines属性的布局大小超过了布局约束,则尝试在[minFontSize](#minfontsize)和[maxFontSize](#maxfontsize)的范围内缩小字体以显示更多文本。
542
543- MIN_FONT_SIZE_FIRST模式:优先使用minFontSize属性来调整文本高度。如果使用minFontSize属性可以将文本布局在一行中,则尝试在minFontSize和maxFontSize的范围内增大字体并使用最大可能的字体大小在一行内显示,否则按minFontSize显示。
544
545- LAYOUT_CONSTRAINT_FIRST模式:优先使用布局约束来调整文本高度。如果布局大小超过布局约束,则尝试在minFontSize和maxFontSize的范围内缩小字体以满足布局约束。如果将字体大小缩小到minFontSize后,布局大小仍然超过布局约束,则删除超过布局约束的行。
546
547**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
548
549**系统能力:** SystemCapability.ArkUI.ArkUI.Full
550
551**参数:**
552
553| 参数名 | 类型                                                         | 必填 | 说明                                                         |
554| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
555| value  | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | 是   | 文本自适应高度的方式。<br/>默认值:TextHeightAdaptivePolicy.MAX_LINES_FIRST |
556
557### textIndent<sup>10+</sup>
558
559textIndent(value: Length)
560
561设置首行文本缩进。
562
563**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
564
565**系统能力:** SystemCapability.ArkUI.ArkUI.Full
566
567**参数:**
568
569| 参数名 | 类型                         | 必填 | 说明                         |
570| ------ | ---------------------------- | ---- | ---------------------------- |
571| value  | [Length](ts-types.md#length) | 是   | 首行文本缩进。<br/>默认值:0 |
572
573### wordBreak<sup>11+</sup>
574
575wordBreak(value: WordBreak)
576
577设置断行规则。
578
579默认情况下,不调用wordBreak或者设置WordBreak.BREAK_WORD时,文本截断按字进行。例如,英文以单词为最小单位进行截断。
580
581WordBreak.BREAK_ALL与{overflow:&nbsp;TextOverflow.Ellipsis}、maxLines组合使用,可实现英文单词按字母截断,超出部分以省略号显示。
582
583**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
584
585**系统能力:** SystemCapability.ArkUI.ArkUI.Full
586
587**参数:**
588
589| 参数名 | 类型                                          | 必填 | 说明                                          |
590| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
591| value  | [WordBreak](ts-appendix-enums.md#wordbreak11) | 是   | 断行规则。 <br />默认值:WordBreak.BREAK_WORD |
592
593### selection<sup>11+</sup>
594
595selection(selectionStart: number, selectionEnd: number)
596
597设置选中区域。
598
599选中区域高亮且显示手柄和文本选择菜单。
600
601当copyOption设置为CopyOptions.None时,设置selection属性不生效。
602
603当overflow设置为TextOverflow.MARQUEE时,设置selection属性不生效。
604
605当selectionStart大于等于selectionEnd时不选中。可选范围为[0, textSize],其中textSize为文本内容最大字符数,入参小于0时处理为0,大于textSize时处理为textSize。
606
607当selectionStart或selectionEnd位于截断的不可见区域时,文本不选中。截断为false时,超出父组件的文本选中区域生效。
608
609可通过[onTextSelectionChange](#ontextselectionchange11)接口获取选区位置变化结果。
610
611**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
612
613**系统能力:** SystemCapability.ArkUI.ArkUI.Full
614
615**参数:**
616
617| 参数名         | 类型   | 必填 | 说明                                 |
618| -------------- | ------ | ---- | ------------------------------------ |
619| selectionStart | number | 是   | 所选文本的起始位置。<br />默认值:-1 |
620| selectionEnd   | number | 是   | 所选文本的结束位置。<br />默认值:-1 |
621
622### ellipsisMode<sup>11+</sup>
623
624ellipsisMode(value: EllipsisMode)
625
626设置省略位置。
627
628ellipsisMode属性需要与overflow设置为TextOverflow.Ellipsis以及maxLines使用,单独设置ellipsisMode属性不生效。
629
630EllipsisMode.STARTEllipsisMode.CENTER仅在单行超长文本生效。
631
632**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
633
634**系统能力:** SystemCapability.ArkUI.ArkUI.Full
635
636**参数:**
637
638| 参数名 | 类型                                                | 必填 | 说明                                      |
639| ------ | --------------------------------------------------- | ---- | ----------------------------------------- |
640| value  | [EllipsisMode](ts-appendix-enums.md#ellipsismode11) | 是   | 省略位置。 <br />默认值:EllipsisMode.END |
641
642### enableDataDetector<sup>11+</sup>
643
644enableDataDetector(enable: boolean)
645
646设置是否进行文本特殊实体识别。
647
648该接口依赖设备底层应具有文本识别能力,否则设置不会生效。
649
650当enableDataDetector设置为true,同时不设置[dataDetectorConfig](#datadetectorconfig11)属性时,默认识别所有类型的实体,所识别实体的color和decoration会被更改为如下样式:
651
652```ts
653color: '#ff007dff'
654decoration:{
655  type: TextDecorationType.Underline,
656  color: '#ff007dff',
657  style: TextDecorationStyle.SOLID
658}
659```
660
661触摸点击和鼠标右键点击实体,会根据实体类型弹出对应的实体操作菜单,鼠标左键点击实体会直接响应菜单的第一个选项。
662
663当overflow设置为TextOverflow.MARQUEE时,该功能不会生效。
664
665当copyOption设置为CopyOptions.None时,点击实体弹出的菜单不包含选择文本、复制、翻译、分享和搜索功能。当copyOption不为CopyOptions.None,且textSelectable设置为TextSelectableMode.UNSELECTABLE时,仍然具有实体复制功能,但不包含选择文本功能。
666<!--RP2--><!--RP2End-->
667
668**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
669
670**系统能力:** SystemCapability.ArkUI.ArkUI.Full
671
672**参数:**
673
674| 参数名 | 类型    | 必填 | 说明                              |
675| ------ | ------- | ---- | --------------------------------- |
676| enable  | boolean | 是   | 使能文本识别。<br/>true表示文本可实体识别,false表示不可识别。<br/>默认值:false |
677
678### dataDetectorConfig<sup>11+</sup>
679
680dataDetectorConfig(config: TextDataDetectorConfig)
681
682设置文本识别配置,可配置识别类型、实体显示样式,以及是否开启长按预览等。
683
684需配合[enableDataDetector](#enabledatadetector11)一起使用,设置enableDataDetector为true时,dataDetectorConfig的配置才能生效。
685
686**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
687
688**系统能力:** SystemCapability.ArkUI.ArkUI.Full
689
690**参数:**
691
692| 参数名 | 类型                                                        | 必填 | 说明                                                         |
693| ------ | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
694| config | [TextDataDetectorConfig](ts-text-common.md#textdatadetectorconfig11对象说明) | 是   | 文本识别配置。|
695
696### bindSelectionMenu<sup>11+</sup>
697
698bindSelectionMenu(spanType: TextSpanType, content: CustomBuilder, responseType: TextResponseType,
699    options?: SelectionMenuOptions)
700
701设置自定义选择菜单。
702
703bindSelectionMenu的长按响应时长为600ms,bindContextMenu的长按响应时长为800ms,当两者同时绑定且触发方式均为长按时,优先响应bindSelectionMenu。
704
705自定义菜单超长时,建议内部嵌套使用[Scroll](./ts-container-scroll.md)组件,避免键盘被遮挡。
706
707**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
708
709**系统能力:** SystemCapability.ArkUI.ArkUI.Full
710
711**参数:**
712
713| 参数名       | 类型                                                         | 必填 | 说明                                                         |
714| ------------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
715| spanType     | [TextSpanType](#textspantype11枚举说明)          | 是   | 选择菜单的类型。<br/>默认值:TextSpanType.TEXT               |
716| content      | [CustomBuilder](ts-types.md#custombuilder8)                  | 是   | 选择菜单的内容。                                             |
717| responseType | [TextResponseType](#textresponsetype11枚举说明)  | 是   | 选择菜单的响应类型。<br/>默认值:TextResponseType.LONG_PRESS |
718| options      | [SelectionMenuOptions](ts-basic-components-richeditor.md#selectionmenuoptions) | 否   | 选择菜单的选项。                                             |
719
720>  **说明:**
721>
722>  通过[editMenuOptions](#editmenuoptions12)设置文本选择菜单时,保留系统默认的风格,触发菜单弹出的条件不变。
723>
724>  通过[bindSelectionMenu](#bindselectionmenu11)设置文本选择菜单时,风格由开发者定义,触发菜单弹出的条件由开发者定义。
725
726### fontFeature<sup>12+</sup>
727
728fontFeature(value: string)
729
730设置文字特性效果,比如数字等宽的特性。
731
732格式为:normal \| \<feature-tag-value\>
733
734\<feature-tag-value\>的格式为:\<string\> \[ \<integer\> \| on \| off ]
735
736\<feature-tag-value\>的个数可以有多个,中间用','隔开。
737
738例如,使用等宽数字的输入格式为:"ss01" on。
739
740**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
741
742**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
743
744**系统能力:** SystemCapability.ArkUI.ArkUI.Full
745
746**参数:**
747
748| 参数名 | 类型   | 必填 | 说明           |
749| ------ | ------ | ---- | -------------- |
750| value  | string | 是   | 文字特性效果。 |
751
752fontFeature属性列表:
753
754![alt text](figures/arkts-fontfeature.png)
755
756设置fontFeature属性,fontFeature是OpenType字体的高级排版能力,如支持连字、数字等宽等特性,一般用在自定义字体中,其能力需要字体本身支持。
757更多fontFeature能力介绍可参考[font-feature-settings property](https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop)和[OpenType Features](https://sparanoid.com/lab/opentype-features/)758
759>  **说明:**
760>
761>  不支持Text内同时存在文本内容和Span或ImageSpan子组件。如果同时存在,只显示Span或ImageSpan内的内容。
762>
763>  字体排版引擎会对开发者传入的宽度[width](ts-universal-attributes-size.md#width)进行向下取整,保证是整型像素后进行排版。如果向上取整,可能会出现文字右侧被截断。
764>
765>  当多个Text组件在[Row](ts-container-row.md)容器内布局且没有设置具体的布局分配信息时,Text会以Row的最大尺寸进行布局。如果需要子组件主轴累加的尺寸不超过Row容器主轴的尺寸,可以设置[layoutWeight](ts-universal-attributes-size.md#layoutweight)或者是以[Flex](ts-universal-attributes-flex-layout.md)布局来约束子组件的主轴尺寸。
766>
767>  系统默认字体支持的liga连字:Th fb ff fb ffb ffh ffi ffk ffl fh fi fk。常导致Span、属性字符串的效果不符合预期,关闭liga连字特性可以规避。
768>
769>  文字特性效果与使用的字体文件密切相关。例如,8标点挤压功能在当前系统默认字体中仅对左侧标点符号生效,而右侧标点符号及感叹号、顿号、问号均不生效。
770
771### lineSpacing<sup>12+</sup>
772
773lineSpacing(value: LengthMetrics)
774
775设置文本的行间距,设置值不大于0时,取默认值0。
776
777**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
778
779**系统能力:** SystemCapability.ArkUI.ArkUI.Full
780
781**参数:**
782
783| 参数名 | 类型                                                         | 必填 | 说明             |
784| ------ | ------------------------------------------------------------ | ---- | ---------------- |
785| value  | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 是   | 文本的行间距。默认值:0 |
786
787### lineSpacing<sup>20+</sup>
788
789lineSpacing(value: LengthMetrics, options?: LineSpacingOptions)
790
791设置文本的行间距。当不配置LineSpacingOptions时,首行上方和尾行下方默认会有行间距。
792
793**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
794
795**系统能力:** SystemCapability.ArkUI.ArkUI.Full
796
797**参数:**
798
799| 参数名 | 类型                                                         | 必填 | 说明             |
800| ------ | ------------------------------------------------------------ | ---- | ---------------- |
801| value  | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 是   | 文本的行间距。设置值不大于0时,取默认值0。 |
802| options  | [LineSpacingOptions](ts-text-common.md#linespacingoptions20对象说明) | 否   | 设置行间距配置项。<br/>默认值:{&nbsp;onlyBetweenLines:&nbsp;false&nbsp;} |
803
804### privacySensitive<sup>12+</sup>
805
806privacySensitive(supported: boolean)
807
808设置是否支持卡片敏感隐私信息。
809
810**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
811
812**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
813
814**系统能力:** SystemCapability.ArkUI.ArkUI.Full
815
816**参数:**
817
818| 参数名    | 类型    | 必填 | 说明                                                         |
819| --------- | ------- | ---- | ------------------------------------------------------------ |
820| supported | boolean | 是   | 是否支持卡片敏感隐私信息。<br/>默认值为false,当设置为true时,隐私模式下文字将被遮罩为横杠“-”样式。<br/>**说明:** <br/>设置为null则表示不敏感。<br/>进入隐私模式需要[卡片框架支持](./ts-universal-attributes-obscured.md)。 |
821
822### lineBreakStrategy<sup>12+</sup>
823
824lineBreakStrategy(strategy: LineBreakStrategy)
825
826设置折行规则。该属性在[wordBreak](#wordbreak11)不等于WordBreak.BREAK_ALL的时候生效,且不支持连词符。
827
828**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
829
830**系统能力:** SystemCapability.ArkUI.ArkUI.Full
831
832**参数:**
833
834| 参数名   | 类型                                                         | 必填 | 说明                                                    |
835| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------- |
836| strategy | [LineBreakStrategy](ts-appendix-enums.md#linebreakstrategy12) | 是   | 文本的折行规则。 <br />默认值:LineBreakStrategy.GREEDY |
837
838### textSelectable<sup>12+</sup>
839
840textSelectable(mode: TextSelectableMode)
841
842设置是否支持文本可选择、可获焦。
843
844需配合[copyOption](#copyoption9)使用。
845
846**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
847
848**系统能力:** SystemCapability.ArkUI.ArkUI.Full
849
850**参数:**
851
852| 参数名 | 类型                                          | 必填 | 说明                                          |
853| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
854| mode  | [TextSelectableMode](ts-appendix-enums.md#textselectablemode12) | 是   | 文本是否支持可选择、可获焦。 <br />默认值:TextSelectableMode.SELECTABLE_UNFOCUSABLE |
855
856### editMenuOptions<sup>12+</sup>
857
858editMenuOptions(editMenu: EditMenuOptions)
859
860设置自定义菜单扩展项,允许用户设置扩展项的文本内容、图标、回调方法。
861
862调用[disableMenuItems](../arkts-apis-uicontext-textmenucontroller.md#disablemenuitems20)或[disableSystemServiceMenuItems](../arkts-apis-uicontext-textmenucontroller.md#disablesystemservicemenuitems20)接口屏蔽文本选择菜单内的系统服务菜单项时,editMenuOptions接口内回调方法[onCreateMenu](./ts-text-common.md#oncreatemenu12)的入参列表中不包含被屏蔽的菜单选项。
863
864**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
865
866**系统能力:** SystemCapability.ArkUI.ArkUI.Full
867
868**参数:**
869
870| 参数名 | 类型                                          | 必填 | 说明                                          |
871| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
872| editMenu  | [EditMenuOptions](ts-text-common.md#editmenuoptions) | 是   | 扩展菜单选项。 |
873
874>  **说明:**
875>
876>  通过[editMenuOptions](#editmenuoptions12)设置文本选择菜单时,保留系统默认的风格,触发菜单弹出的条件不变。
877>
878>  通过[bindSelectionMenu](#bindselectionmenu11)设置文本选择菜单时,风格由开发者定义,触发菜单弹出的条件由开发者定义。
879
880### minFontScale<sup>12+</sup>
881
882minFontScale(scale: number | Resource)
883
884设置文本最小的字体缩放倍数。
885
886**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
887
888**系统能力:** SystemCapability.ArkUI.ArkUI.Full
889
890**参数:**
891
892| 参数名 | 类型                                          | 必填 | 说明                                          |
893| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
894| scale  | number \| [Resource](ts-types.md#resource) | 是   | 文本最小的字体缩放倍数。<br/>取值范围:[0, 1]<br/>**说明:** <br/>设置的值小于0时按0处理,大于1时按1处理,其余异常值默认不生效。 |
895
896### maxFontScale<sup>12+</sup>
897
898maxFontScale(scale: number | Resource)
899
900设置文本最大的字体缩放倍数。
901
902**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
903
904**系统能力:** SystemCapability.ArkUI.ArkUI.Full
905
906**参数:**
907
908| 参数名 | 类型                                          | 必填 | 说明                                          |
909| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
910| scale  | number \| [Resource](ts-types.md#resource) | 是   | 文本最大的字体缩放倍数。<br/>取值范围:[1, +∞)<br/>**说明:** <br/>设置的值小于1时,按值为1处理,其余异常值默认不生效。 |
911
912### halfLeading<sup>12+</sup>
913
914halfLeading(halfLeading: boolean)
915
916设置文本是否将行间距平分至行的顶部与底部。
917
918**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
919
920**系统能力:** SystemCapability.ArkUI.ArkUI.Full
921
922**参数:**
923
924| 参数名 | 类型                                          | 必填 | 说明                                          |
925| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
926| halfLeading | boolean | 是  | 文本是否将行间距平分至行的顶部与底部。<br/>true表示将行间距平分至行的顶部与底部,false则不平分。<br/>默认值:false |
927
928### font<sup>12+</sup>
929
930font(fontValue: Font, options?: FontSettingOptions)
931
932设置文本样式,支持设置字体配置项。
933
934仅Text组件生效,其子组件不生效。
935
936**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
937
938**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
939
940**系统能力:** SystemCapability.ArkUI.ArkUI.Full
941
942**参数:**
943
944| 参数名 | 类型                                          | 必填 | 说明                                          |
945| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
946| fontValue | [Font](ts-types.md#font) | 是  | 设置文本样式。 |
947| options | [FontSettingOptions](ts-text-common.md#fontsettingoptions12对象说明) | 否  | 设置字体配置项。 |
948
949### fontWeight<sup>12+</sup>
950
951fontWeight(weight: number | FontWeight | ResourceStr, options?: FontSettingOptions)
952
953设置文本字重,支持设置字体配置项。
954
955仅Text组件生效,其子组件不生效。
956
957**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
958
959**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
960
961**系统能力:** SystemCapability.ArkUI.ArkUI.Full
962
963**参数:**
964
965| 参数名 | 类型                                          | 必填 | 说明                                          |
966| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
967| weight | number&nbsp;\|&nbsp;[FontWeight](ts-appendix-enums.md#fontweight)&nbsp;\|&nbsp;[ResourceStr](ts-types.md#resourcestr) | 是  | 设置文本字重。number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。 <br>从API version 20开始,支持Resource类型。|
968| options | [FontSettingOptions](ts-text-common.md#fontsettingoptions12对象说明) | 否  | 设置字体配置项。 |
969
970### enableHapticFeedback<sup>13+</sup>
971
972enableHapticFeedback(isEnabled: boolean)
973
974设置是否开启触控反馈。
975
976**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
977
978**系统能力:** SystemCapability.ArkUI.ArkUI.Full
979
980**参数:**
981
982| 参数名 | 类型    | 必填 | 说明                               |
983| ------ | ------- | ---- | ---------------------------------- |
984| isEnabled | boolean | 是   | 是否开启触控反馈。<br/>true表示开启,false表示不开启。<br/>默认值:true |
985
986>  **说明:**
987>
988>  开启触控反馈时,需要在工程的module.json5中配置requestPermissions字段开启振动权限,配置如下:
989> ```json
990> "requestPermissions": [
991>  {
992>     "name": "ohos.permission.VIBRATE",
993>  }
994> ]
995> ```
996
997### optimizeTrailingSpace<sup>20+</sup>
998
999optimizeTrailingSpace(optimize: Optional\<boolean>)
1000
1001设置是否在文本布局过程中优化每行末尾的空格,可解决行尾空格影响对齐显示效果问题。
1002
1003设置Text.optimizeTrailingSpace为true时:
1004
1005* 多行、单行、图文混排等多种情况下均会优化行尾空格(TextAlign.CenterTextAlign.End时,优化效果明显);
1006
1007* 纯空格文本时,修饰线、阴影、背景色跟随空格文本显示;
1008
1009* 行首空格不在优化范围内,行尾文本强制换行,每行行尾空格根据组件宽度优化行尾空格。
1010
1011当纯空格文本设置优化行尾空格[optimizeTrailingSpace](#optimizetrailingspace20)为true时,不允许同时设置文本背景色[backgroundColor](ts-universal-attributes-background.md#backgroundcolor)、空格装饰线[decoration](#decoration)和对齐[textAlign](#textalign)三个属性。
1012
1013**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
1014
1015**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1016
1017**参数:**
1018
1019| 参数名           | 类型             | 必填 | 说明                                            |
1020| ---------------- | ------- | ---- | ----------------------------------------------- |
1021| optimize         | [Optional](ts-universal-attributes-custom-property.md#optionalt12)\<boolean> | 是   | 是否优化每行末尾的空格。<br/>true表示优化末尾空格,false则不优化。<br/>默认值:false |
1022
1023### caretColor<sup>14+</sup>
1024
1025caretColor(color: ResourceColor)
1026
1027设置文本框选中区域手柄颜色。
1028
1029**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
1030
1031**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1032
1033**参数:**
1034
1035| 参数名 | 类型                                       | 必填 | 说明                                   |
1036| ------ | ------------------------------------------ | ---- | -------------------------------------- |
1037| color  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 文本选中手柄颜色。<br/>默认值:'#007DFF' |
1038
1039### selectedBackgroundColor<sup>14+</sup>
1040
1041selectedBackgroundColor(color: ResourceColor)
1042
1043设置文本选中底板颜色。如果未设置不透明度,默认为20%不透明度。
1044
1045**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
1046
1047**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1048
1049**参数:**
1050
1051| 参数名 | 类型                                       | 必填 | 说明                                       |
1052| ------ | ------------------------------------------ | ---- | ------------------------------------------ |
1053| color  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 文本选中底板颜色。<br/>默认值:'#007DFF' |
1054
1055### marqueeOptions<sup>18+</sup>
1056
1057marqueeOptions(options: Optional\<TextMarqueeOptions>)
1058
1059设置文本跑马灯模式的配置项。
1060
1061当textOverflow设置为TextOverflow.MARQUEE时,marqueeOptions的设置才能生效。
1062
1063**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
1064
1065**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1066
1067**参数:**
1068
1069| 参数名 | 类型                                       | 必填 | 说明                                       |
1070| ------ | ------------------------------------------ | ---- | ------------------------------------------ |
1071| options | [Optional](ts-universal-attributes-custom-property.md#optionalt12)\<[TextMarqueeOptions](#textmarqueeoptions18对象说明)> | 是 | 当Text组件的textOverflow属性设置为MARQUEE时,可通过marqueeOptions设置跑马灯动效具体的属性,如开关、步长、循环次数、方向等。 |
1072
1073### enableAutoSpacing<sup>20+</sup>
1074
1075enableAutoSpacing(enabled: Optional\<boolean>)
1076
1077设置是否开启中文与西文的自动间距。
1078
1079**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
1080
1081**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1082
1083**参数:**
1084
1085| 参数名 | 类型    | 必填 | 说明                               |
1086| ------ | ------- | ---- | ---------------------------------- |
1087| enabled | [Optional](ts-universal-attributes-custom-property.md#optionalt12)\<boolean> | 是   | 是否开启中文与西文的自动间距。<br/>true为开启自动间距,false为不开启。<br />默认值:false |
1088
1089### shaderStyle<sup>20+</sup>
1090
1091shaderStyle(shader: ShaderStyle)
1092
1093可以显示为径向渐变[RadialGradientStyle](../arkui-ts/ts-text-common.md#radialgradientstyle20)或线性渐变[LinearGradientStyle](../arkui-ts/ts-text-common.md#lineargradientstyle20)或纯色[ColorShaderStyle](../arkui-ts/ts-text-common.md#colorshaderstyle20)的效果,shaderStyle的优先级高于[fontColor](../arkui-ts/ts-basic-components-symbolSpan.md#fontcolor)和AI识别,纯色建议使用[fontColor](../arkui-ts/ts-basic-components-symbolSpan.md#fontcolor)。
1094
1095**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
1096
1097**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1098
1099**参数:**
1100
1101| 参数名     | 类型                                         | 必填                             | 说明                               |
1102| -------------- | -------------------------------------------- | ----------------------------------- | ----------------------------------- |
1103| shader | [ShaderStyle](../arkui-ts/ts-text-common.md#shaderstyle20) | 是 | 径向渐变或线性渐变或纯色。<br/>根据传入的参数区分处理径向渐变[RadialGradientStyle](../arkui-ts/ts-text-common.md#radialgradientstyle20)或线性渐变[LinearGradientStyle](../arkui-ts/ts-text-common.md#lineargradientstyle20)或纯色[ColorShaderStyle](../arkui-ts/ts-text-common.md#colorshaderstyle20),最终设置到Text文本上显示为渐变色效果。<br/>**说明:** <br/>当设置为径向渐变[RadialGradientStyle](../arkui-ts/ts-text-common.md#radialgradientstyle20)时,若[RadialGradientOptions](./ts-universal-attributes-gradient-color.md#radialgradientoptions18对象说明)的center参数设置到组件范围外时,可将repeating参数设置为true,此时渐变效果会更明显。 |
1104
1105## TextSpanType<sup>11+</sup>枚举说明
1106
1107[Span](ts-basic-components-span.md)类型信息。
1108
1109**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1110
1111| 名称 | 值 | 说明 |
1112| -------- | ---- | -------- |
1113| TEXT | 0 | Span为文字类型。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
1114| IMAGE | 1 | Span为图像类型。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
1115| MIXED | 2 | Span为图文混合类型。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
1116| DEFAULT<sup>15+</sup> | 3 | 注册此类型菜单但未注册TEXT、IMAGE、MIXED菜单时,文字类型、图片类型、图文混合类型都会触发并显示此类型对应的菜单。<br/>**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 |
1117
1118>  **说明:**
1119>
1120>  菜单类型的匹配顺序如下。例如,用户长按文本时,根据以下规则查找:
1121>  1. 查找是否注册了TextSpanType.TEXTTextResponseType.LONG_PRESS菜单
1122>  2. 查找是否注册了TextSpanType.TEXTTextResponseType.DEFAULT菜单
1123>  3. 查找是否注册了TextSpanType.DEFAULTTextResponseType.LONG_PRESS菜单
1124>  4. 查找是否注册了TextSpanType.DEFAULTTextResponseType.DEFAULT菜单
1125
1126## TextResponseType<sup>11+</sup>枚举说明
1127
1128选择菜单的响应类型。
1129
1130**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1131
1132| 名称         | 值 |  说明          |
1133| ---------- | --- | ------------- |
1134| RIGHT_CLICK | 0 | 通过鼠标右键触发菜单弹出。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
1135| LONG_PRESS  | 1 | 通过长按触发菜单弹出。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
1136| SELECT | 2 | 通过鼠标选中触发菜单弹出。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
1137| DEFAULT<sup>15+</sup> | 3 | 注册此类型的菜单,但未注册RIGHT_CLICK、LONG_PRESS、SELECT时,右键、长按、鼠标选中均会触发并显示此类型对应的菜单。<br/>**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 |
1138
1139>  **说明:**
1140>
1141>  菜单类型的匹配顺序如下。例如,用户长按文本时,根据以下规则查找:
1142>  1. 查找是否注册了TextSpanType.TEXTTextResponseType.LONG_PRESS菜单
1143>  2. 查找是否注册了TextSpanType.TEXTTextResponseType.DEFAULT菜单
1144>  3. 查找是否注册了TextSpanType.DEFAULTTextResponseType.LONG_PRESS菜单
1145>  4. 查找是否注册了TextSpanType.DEFAULTTextResponseType.DEFAULT菜单
1146
1147## TextOverflowOptions<sup>18+</sup>对象说明
1148
1149文本超长显示方式对象。
1150
1151> **说明:**
1152>
1153> 为规范匿名对象的定义,API 18版本修改了此处的元素定义。其中,保留了历史匿名对象的起始版本信息,会出现外层元素@since版本号高于内层元素版本号的情况,但这不影响接口的使用。
1154
1155**卡片能力:** 从API version 18开始,该接口支持在ArkTS卡片中使用。
1156
1157**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
1158
1159**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1160
1161| 名称 | 类型                                                         | 只读 | 可选 | 说明                                                         |
1162| ------ | ------------------------------------------------------------ | ---- |---- | ------------------------------------------------------------ |
1163| overflow<sup>7+</sup>  | [TextOverflow](ts-appendix-enums.md#textoverflow) | 否 | 否  | 文本超长时的显示方式。<br/>默认值:TextOverflow.Clip <br/>**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
1164
1165## 事件
1166
1167除支持[通用事件](ts-component-general-events.md)外,还支持以下事件:
1168
1169### onCopy<sup>11+</sup>
1170
1171onCopy(callback:(value:&nbsp;string)&nbsp;=&gt;&nbsp;void)
1172
1173长按文本内部区域弹出剪贴板后,点击剪贴板复制按钮,触发该回调。目前只有文本可以复制。
1174
1175**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1176
1177**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1178
1179**参数:**
1180
1181| 参数名 | 类型   | 必填 | 说明             |
1182| ------ | ------ | ---- | ---------------- |
1183| value  | string | 是   | 复制的文本内容。 |
1184
1185### onTextSelectionChange<sup>11+</sup>
1186
1187onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)
1188
1189文本选择的位置发生变化时,触发该回调。
1190
1191**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1192
1193**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1194
1195**参数:**
1196
1197| 参数名         | 类型   | 必填 | 说明                 |
1198| -------------- | ------ | ---- | -------------------- |
1199| selectionStart | number | 是   | 所选文本的起始位置。 |
1200| selectionEnd   | number | 是   | 所选文本的结束位置。 |
1201
1202### onMarqueeStateChange<sup>18+</sup>
1203
1204onMarqueeStateChange(callback: Callback\<MarqueeState\>)
1205
1206跑马灯动画进行到特定的阶段时,触发该回调。
1207
1208**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
1209
1210**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1211
1212**参数:**
1213
1214| 参数名    | 类型                                             | 必填  | 说明                       |
1215|--------|---------------------------------------------------|-----|--------------------------|
1216| callback  | Callback\<[MarqueeState](#marqueestate18枚举说明)\> | 是   | 通过callback参数指定触发回调的状态,状态由MarqueeState枚举定义,例如开始滚动、滚动一次、滚动完成。 |
1217
1218## TextOptions<sup>11+</sup>
1219
1220Text初始化参数。
1221
1222**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1223
1224**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1225
1226| 名称 | 类型 | 只读 | 可选 | 说明 |
1227| -------- | -------- | -------- | -------- | -------- |
1228| controller | [TextController](#textcontroller11)  | 否 | 否 | 文本控制器。 |
1229
1230## TextController<sup>11+</sup>
1231
1232Text组件的控制器。
1233
1234**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1235
1236**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1237
1238### 导入对象
1239
1240```
1241controller: TextController = new TextController()
1242```
1243
1244### closeSelectionMenu
1245
1246closeSelectionMenu(): void
1247
1248关闭自定义选择菜单或系统默认选择菜单。
1249
1250**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1251
1252**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1253
1254### setStyledString<sup>12+</sup>
1255
1256setStyledString(value: StyledString): void
1257
1258触发绑定或更新属性字符串。
1259
1260**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1261
1262**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1263
1264**参数:**
1265
1266| 参数名   | 类型   | 必填   | 说明                |
1267| ----- | ------ | ---- | ------------------- |
1268| value | [StyledString](ts-universal-styled-string.md#styledstring) | 是    | 属性字符串。<br/>**说明:** <br/>StyledString的子类[MutableStyledString](ts-universal-styled-string.md#mutablestyledstring)也可以作为入参值。 |
1269
1270>  **说明:**
1271>  多次调用setStyledString,会用新的入参覆盖已绑定的属性字符串,而不是叠加新的入参。
1272>
1273>  属性字符串通过controller绑定时,需要等待布局完成后,绑定生效。当[measure](../js-apis-arkui-frameNode.md#measure12)和setStyledString同时使用,开发者需要通过[@ohos.arkui.inspector (布局回调)](../js-apis-arkui-inspector.md)判断布局完成,再绑定属性字符串。
1274>
1275>  在API version 14及以下版本,开发者调用TextController的setStyledString接口设置属性字符串,如果调用时TextController还未绑定对应的Text,则此次设置无效。
1276>
1277>  从API version 15开始,TextController会保存设置的属性字符串。当TextController已经和Text绑定,则Text会自动设置属性字符串,显示对应的样式。
1278>
1279>  这一区别体现在[aboutToAppear](./ts-custom-component-lifecycle.md#abouttoappear)中设置属性字符串,API 14及以下版本不生效,API 15及以上版本生效,推荐用法请参考[创建并应用StyledString和MutableStyledString](../../../ui/arkts-styled-string.md#创建并应用styledstring和mutablestyledstring)。
1280
1281
1282
1283### getLayoutManager<sup>12+</sup>
1284
1285getLayoutManager(): LayoutManager
1286
1287获取布局管理器对象。
1288
1289**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1290
1291**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1292
1293**返回值:**
1294
1295| 类型                                       | 说明      |
1296| ---------------------------------------- | ------- |
1297| [LayoutManager](ts-text-common.md#layoutmanager12) | 布局管理器对象。 |
1298
1299## TextMarqueeOptions<sup>18+</sup>对象说明
1300
1301Marquee初始化参数。
1302
1303**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
1304
1305**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1306
1307| 名称                | 类型                                              | 只读 | 可选 | 说明                                                                                  |
1308|--------------------|-------------------------------------------------|----|----|-------------------------------------------------------------------------------------|
1309| start              | boolean                                         | 否  | 否 | 控制跑马灯进入播放状态。<br/>true表示播放,false表示不播放。                           |
1310| step               | number                                          | 否  | 是 | 滚动动画文本滚动步长。<br/>默认值:4.0vp                                                           |
1311| loop               | number                                          | 否  | 是 | 设置重复滚动的次数,小于等于零时无限循环。<br/>默认值:-1                                                    |
1312| fromStart          | boolean                                         | 否  | 是 | 设置文本从头开始滚动或反向滚动。<br/>true表示从头开始滚动,false表示反向滚动。<br/>默认值:true                                                  |
1313| delay              | number                                          | 否  | 是 | 设置每次滚动的时间间隔。<br/>默认值:0 <br/>单位:毫秒                                                             |
1314| fadeout            | boolean                                         | 否  | 是 | 设置文字超长时的渐隐效果。<br/>true表示支持渐隐效果,false表示不支持渐隐效果。<br/>当Text内容超出显示范围时,未完全展现的文字边缘将应用渐隐效果。若两端均有文字未完全显示,则两端同时应用渐隐效果。在渐隐效果开启状态下,clip属性将自动锁定为true,不允许设置为false。<br/>默认值:false  |
1315| marqueeStartPolicy | [MarqueeStartPolicy](#marqueestartpolicy18枚举说明) | 否  | 是 | 设置跑马灯启动策略。<br/>默认值:MarqueeStartPolicy.DEFAULT                                       |
1316
1317## MarqueeStartPolicy<sup>18+</sup>枚举说明
1318
1319Marquee的滚动方式,可选择默认持续滚动或条件触发滚动。
1320
1321**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
1322
1323**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1324
1325| 名称        | 值 | 说明            |
1326|----------|----|---------------|
1327| DEFAULT  | 0  | 默认持续滚动。       |
1328| ON_FOCUS | 1  | 获焦以及鼠标悬浮时开始滚动。 |
1329
1330## MarqueeState<sup>18+</sup>枚举说明
1331
1332Marquee状态回调的返回值。
1333
1334**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
1335
1336**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1337
1338| 名称     | 值 | 说明                            |
1339|--------|----|-------------------------------|
1340| START  | 0  | 跑马灯滚动开始。                     |
1341| BOUNCE | 1  | 完成一次跑马灯滚动,如果循环次数不是1,将会多次返回。 |
1342| FINISH | 2  | 跑马灯全部循环次数完成。              |
1343
1344## 示例
1345
1346### 示例1(设置文本布局)
1347该示例通过[textAlign](#textalign)、[lineHeight](#lineheight)、[baselineOffset](#baselineoffset)、[halfLeading](#halfleading12)(从API version 12开始)属性展示了文本布局的效果。
1348```ts
1349// xxx.ets
1350@Extend(Text)
1351function style(TextAlign: TextAlign) {
1352  .textAlign(TextAlign)
1353  .fontSize(12)
1354  .border({ width: 1 })
1355  .padding(10)
1356  .width('100%')
1357  .margin(5)
1358}
1359
1360@Entry
1361@Component
1362struct TextExample1 {
1363  @State changeTextAlignIndex: number = 0;
1364  @State changeDecorationIndex: number = 0;
1365  @State textAlign: TextAlign[] = [TextAlign.Start, TextAlign.Center, TextAlign.End];
1366  @State textAlignStr: string[] = ['Start', 'Center', 'End'];
1367
1368  build() {
1369    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1370      // 设置文本水平方向对齐方式
1371      // 单行文本
1372      Text('textAlign').fontSize(9).fontColor(0xCCCCCC)
1373      Text(`TextAlign set to ${this.textAlignStr[this.changeTextAlignIndex]}.`)
1374        .style(this.textAlign[this.changeTextAlignIndex])
1375
1376      // 多行文本
1377      Text(`This is the text content with textAlign set to ${this.textAlignStr[this.changeTextAlignIndex]}.`)
1378        .style(this.textAlign[this.changeTextAlignIndex])
1379        .margin(5)
1380
1381      Row() {
1382        Button('当前TextAlign类型:' + this.textAlignStr[this.changeTextAlignIndex]).onClick(() => {
1383          this.changeTextAlignIndex++;
1384          if (this.changeTextAlignIndex > (this.textAlignStr.length - 1)) {
1385            this.changeTextAlignIndex = 0;
1386          }
1387        })
1388      }.justifyContent(FlexAlign.Center).width('100%')
1389
1390      // 设置文本行高
1391      Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
1392      Text('This is the text with the line height set. This is the text with the line height set.')
1393        .style(TextAlign.Start)
1394      Text('This is the text with the line height set. This is the text with the line height set.')
1395        .style(TextAlign.Start)
1396        .lineHeight(20)
1397
1398      // 设置文本基线偏移
1399      Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC)
1400      Text('This is the text content with baselineOffset 0.')
1401        .baselineOffset(0)
1402        .style(TextAlign.Start)
1403      Text('This is the text content with baselineOffset 30.')
1404        .baselineOffset(30)
1405        .style(TextAlign.Start)
1406      Text('This is the text content with baselineOffset -20.')
1407        .baselineOffset(-20)
1408        .style(TextAlign.Start)
1409
1410      // 设置文本是否居中对齐
1411      Text('halfLeading').fontSize(9).fontColor(0xCCCCCC)
1412      Text("This is the text with the halfLeading set.")
1413        .lineHeight(60)
1414        .halfLeading(true)
1415        .style(TextAlign.Start)
1416      Text("This is the text without the halfLeading set.")
1417        .lineHeight(60)
1418        .halfLeading(false)
1419        .style(TextAlign.Start)
1420    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1421  }
1422}
1423```
1424![textExp1](figures/textExp1.gif)
1425
1426### 示例2(设置文本样式)
1427
1428该示例通过[decoration](#decoration)、[letterSpacing](#letterspacing)、[textCase](#textcase)、[fontFamily](#fontfamily)、[textShadow](#textshadow10)(从API version 10开始)、fontStyle、[textIndent](#textindent10)(从API version 10开始)、[fontWeight](#fontweight12)(从API version 12开始,支持设置字重无极调节配置项)属性展示了不同样式的文本效果。
1429
1430```ts
1431// xxx.ets
1432@Extend(Text)
1433function style() {
1434  .font({ size: 12 })
1435  .border({ width: 1 })
1436  .padding(10)
1437  .width('100%')
1438  .margin(5)
1439}
1440
1441@Entry
1442@Component
1443struct TextExample2 {
1444  @State changeDecorationIndex: number = 0;
1445  @State textDecorationType: TextDecorationType[] =
1446    [TextDecorationType.LineThrough, TextDecorationType.Overline, TextDecorationType.Underline];
1447  @State textDecorationTypeStr: string[] = ['LineThrough', 'Overline', 'Underline'];
1448  @State textDecorationStyle: TextDecorationStyle[] =
1449    [TextDecorationStyle.SOLID, TextDecorationStyle.DOTTED, TextDecorationStyle.WAVY];
1450  @State textDecorationStyleStr: string[] = ['SOLID', 'DOTTED', 'WAVY'];
1451
1452  build() {
1453    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1454      Text('decoration').fontSize(9).fontColor(0xCCCCCC)
1455      Text('This is the text content with the decoration set to LineThrough and the color set to Red.')
1456        .decoration({
1457          type: this.textDecorationType[this.changeDecorationIndex],
1458          color: Color.Red,
1459          style: this.textDecorationStyle[this.changeDecorationIndex]
1460        })
1461        .style()
1462        .margin(5)
1463
1464      Row() {
1465        Button('decoration type:' + this.textDecorationTypeStr[this.changeDecorationIndex] + ' & ' +
1466        this.textDecorationStyleStr[this.changeDecorationIndex]).onClick(() => {
1467          this.changeDecorationIndex++;
1468          if (this.changeDecorationIndex > (this.textDecorationTypeStr.length - 1)) {
1469            this.changeDecorationIndex = 0;
1470          }
1471        })
1472      }.justifyContent(FlexAlign.Center).width('100%')
1473
1474      // 文本字符间距
1475      Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
1476      Text('This is the text content with letterSpacing 0.')
1477        .letterSpacing(0)
1478        .style()
1479      Text('This is the text content with letterSpacing 3.')
1480        .letterSpacing(3)
1481        .style()
1482      Text('This is the text content with letterSpacing -1.')
1483        .letterSpacing(-1)
1484        .style()
1485
1486      Text('textCase').fontSize(9).fontColor(0xCCCCCC)
1487      Text('This is the text content with textCase set to Normal.')
1488        .textCase(TextCase.Normal)
1489        .style()
1490      // 文本全小写展示
1491      Text('This is the text content with textCase set to LowerCase.')
1492        .textCase(TextCase.LowerCase)
1493        .style()
1494      // 文本全大写展示
1495      Text('This is the text content with textCase set to UpperCase.')
1496        .textCase(TextCase.UpperCase)
1497        .style()
1498
1499      Text('fontFamily').fontSize(9).fontColor(0xCCCCCC)
1500      // 设置字体列表
1501      Text('This is the text content with fontFamily')
1502        .style()
1503        .fontFamily('HarmonyOS Sans')
1504
1505      Text('textShadow').fontSize(9).fontColor(0xCCCCCC)
1506      // 设置文字阴影效果
1507      Text('textShadow')
1508        .style()
1509        .textAlign(TextAlign.Center)
1510        .fontSize(40)
1511        .textShadow({
1512          radius: 10,
1513          color: Color.Black,
1514          offsetX: 0,
1515          offsetY: 0
1516        })
1517
1518      Text('fontStyle').fontSize(9).fontColor(0xCCCCCC)
1519      // 设置字体样式
1520      Text('This is the text content with fontStyle set to Italic')
1521        .style()
1522        .fontStyle(FontStyle.Italic)
1523      Text('This is the text content with fontStyle set to Normal')
1524        .style()
1525        .fontStyle(FontStyle.Normal)
1526
1527      Text('textIndent').fontSize(9).fontColor(0xCCCCCC)
1528      // 设置文字缩进
1529      Text('This is the text content with textIndent 30')
1530        .style()
1531        .textIndent(30)
1532
1533      Text('fontWeight').fontSize(9).fontColor(0xCCCCCC)
1534      // 设置文本的字体粗细
1535      Text('This is the text content with fontWeight 800')
1536        .style()
1537        .fontWeight('800', { enableVariableFontWeight: true })
1538
1539    }.width('100%').padding({ left: 35, right: 35 })
1540  }
1541}
1542```
1543![textExp2](figures/textExp2.gif)
1544
1545### 示例3(设置文本超长省略)
1546
1547该示例通过[maxLines](#maxlines)、[textOverflow](#textoverflow)、[ellipsisMode](#ellipsismode11)(从API version 11开始)属性展示了文本超长省略以及调整省略位置的效果,同时,可以通过[marqueeOptions](#marqueeoptions18)(从API version 18开始)配置跑马灯模式下的配置项以及跑马灯动画进行到特定的阶段时,触发的回调[onMarqueeStateChange](#onmarqueestatechange18)(从API version 18开始)。
1548
1549```ts
1550// xxx.ets
1551@Extend(Text)
1552function style() {
1553  .textAlign(TextAlign.Center)
1554  .fontSize(12)
1555  .border({ width: 1 })
1556  .padding(10)
1557  .width('100%')
1558  .margin(5)
1559}
1560
1561@Entry
1562@Component
1563struct TextExample3 {
1564  @State text: string =
1565    'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.';
1566  @State ellipsisModeIndex: number = 0;
1567  @State ellipsisMode: EllipsisMode[] = [EllipsisMode.START, EllipsisMode.CENTER, EllipsisMode.END];
1568  @State ellipsisModeStr: string[] = ['START', 'CENTER', 'END'];
1569
1570  build() {
1571    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1572      // 文本超长时显示方式
1573      Text('TextOverflow+maxLines').fontSize(9).fontColor(0xCCCCCC)
1574      // 超出maxLines截断内容展示
1575      Text('This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content. This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content.')
1576        .textOverflow({ overflow: TextOverflow.Clip })
1577        .maxLines(1)
1578        .style()
1579
1580      // 超出maxLines展示省略号
1581      Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.')
1582        .textOverflow({ overflow: TextOverflow.Ellipsis })
1583        .maxLines(1)
1584        .style()
1585
1586      Text('marquee').fontSize(9).fontColor(0xCCCCCC)
1587      // 设置文本超长时以跑马灯的方式展示
1588      Text('This is the text with the text overflow set marquee')
1589        .textOverflow({ overflow: TextOverflow.MARQUEE })
1590        .style()
1591        .marqueeOptions({
1592          start: true,
1593          fromStart: true,
1594          step: 6,
1595          loop: -1,
1596          delay: 0,
1597          fadeout: false,
1598          marqueeStartPolicy: MarqueeStartPolicy.DEFAULT
1599        })
1600        .onMarqueeStateChange((state: MarqueeState) => {
1601          if (state == MarqueeState.START) {
1602            // "收到状态: START";
1603          } else if (state == MarqueeState.BOUNCE) {
1604            // "收到状态: BOUNCE";
1605          } else if (state == MarqueeState.FINISH) {
1606            // "收到状态: FINISH";
1607          }
1608        })
1609
1610      Text('ellipsisMode').fontSize(9).fontColor(0xCCCCCC)
1611      // 设置文本超长时省略号的位置
1612      Text(this.text)
1613        .textOverflow({ overflow: TextOverflow.Ellipsis })
1614        .ellipsisMode(this.ellipsisMode[this.ellipsisModeIndex])
1615        .maxLines(1)
1616        .style()
1617
1618      Row() {
1619        Button('更改省略号位置:' + this.ellipsisModeStr[this.ellipsisModeIndex]).onClick(() => {
1620          this.ellipsisModeIndex++;
1621          if (this.ellipsisModeIndex > (this.ellipsisModeStr.length - 1)) {
1622            this.ellipsisModeIndex = 0;
1623          }
1624        })
1625      }
1626    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1627  }
1628}
1629```
1630
1631![](figures/textExp3.gif)
1632
1633### 示例4(设置文本断行及折行)
1634
1635该示例通过[wordBreak](#wordbreak11)(从API version 11开始)、[lineBreakStrategy](#linebreakstrategy12)(从API version 12开始)、[clip](ts-universal-attributes-sharp-clipping.md#clip12)属性展示了文本在不同断行、折行规则下的效果以及文本超长时是否截断。
1636
1637```ts
1638// xxx.ets
1639@Extend(Text)
1640function style() {
1641  .fontSize(12)
1642  .border({ width: 1 })
1643  .padding(10)
1644  .width('100%')
1645  .margin(5)
1646}
1647
1648@Entry
1649@Component
1650struct TextExample4 {
1651  @State text: string =
1652    'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.';
1653  @State text2: string =
1654    "They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" +
1655      "The built-in components include buttons radio buttons progress indicators and text You can set the rendering effect of these components in method chaining mode," +
1656      "page components are divided into independent UI units to implement independent creation development and reuse of different units on pages making pages more engineering-oriented.";
1657  @State textClip: boolean = false;
1658  @State wordBreakIndex: number = 0;
1659  @State wordBreak: WordBreak[] = [WordBreak.NORMAL, WordBreak.BREAK_ALL, WordBreak.BREAK_WORD];
1660  @State wordBreakStr: string[] = ['NORMAL', 'BREAK_ALL', 'BREAK_WORD'];
1661  @State lineBreakStrategyIndex: number = 0;
1662  @State lineBreakStrategy: LineBreakStrategy[] =
1663    [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED];
1664  @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED'];
1665
1666  build() {
1667    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1668      Text('wordBreak').fontSize(9).fontColor(0xCCCCCC)
1669      // 设置文本断行规则
1670      Text(this.text)
1671        .maxLines(2)
1672        .textOverflow({ overflow: TextOverflow.Ellipsis })
1673        .wordBreak(this.wordBreak[this.wordBreakIndex])
1674        .style()
1675
1676      Row() {
1677        Button('当前wordBreak模式:' + this.wordBreakStr[this.wordBreakIndex]).onClick(() => {
1678          this.wordBreakIndex++;
1679          if (this.wordBreakIndex > (this.wordBreakStr.length - 1)) {
1680            this.wordBreakIndex = 0;
1681          }
1682        })
1683      }
1684
1685      Text('clip').fontSize(9).fontColor(0xCCCCCC)
1686      // 设置文本是否超长截断
1687      Text('This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.')
1688        .wordBreak(WordBreak.NORMAL)
1689        .maxLines(2)
1690        .clip(this.textClip)
1691        .style()
1692      Row() {
1693        Button('切换clip:' + this.textClip).onClick(() => {
1694          this.textClip = !this.textClip;
1695        })
1696      }
1697
1698      Text('lineBreakStrategy').fontSize(9).fontColor(0xCCCCCC)
1699      // 设置文本折行规则
1700      Text(this.text2)
1701        .lineBreakStrategy(this.lineBreakStrategy[this.lineBreakStrategyIndex])
1702        .style()
1703      Row() {
1704        Button('当前lineBreakStrategy模式:' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => {
1705          this.lineBreakStrategyIndex++;
1706          if (this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) {
1707            this.lineBreakStrategyIndex = 0;
1708          }
1709        })
1710      }
1711    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1712  }
1713}
1714```
1715
1716![](figures/textExp4.gif)
1717
1718### 示例5(设置文本选中和复制)
1719
1720该示例通过[selection](#selection11)(从API version 11开始)、[onCopy](#oncopy11)(从API version 11开始)、[draggable](#draggable9)(从API version 9开始)、[caretColor](#caretcolor14)(从API version 14开始)、[selectedBackgroundColor](#selectedbackgroundcolor14)(从API version 14开始)接口展示了文本选中、触发复制回调、设置文本选中可拖拽以及修改手柄和选中颜色的效果。
1721
1722```ts
1723// xxx.ets
1724@Entry
1725@Component
1726struct TextExample5 {
1727  @State onCopy: string = '';
1728  @State text: string =
1729    'This is set selection to Selection text content This is set selection to Selection text content.';
1730  @State start: number = 0;
1731  @State end: number = 20;
1732
1733  build() {
1734    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
1735      Text(this.text)
1736        .fontSize(12)
1737        .border({ width: 1 })
1738        .lineHeight(20)
1739        .margin(30)
1740        .copyOption(CopyOptions.InApp)
1741        .selection(this.start, this.end)
1742        .onCopy((value: string) => {
1743          this.onCopy = value;
1744        })
1745        .draggable(true)
1746        .caretColor(Color.Red)
1747        .selectedBackgroundColor(Color.Grey)
1748        .enableHapticFeedback(true)
1749      Button('Set text selection')
1750        .margin({ left: 20 })
1751        .onClick(() => {
1752          // 变更文本选中起始点、终点
1753          this.start = 10;
1754          this.end = 30;
1755        })
1756      Text(this.onCopy).fontSize(12).margin(10).key('copy')
1757    }.height(600).width(335).padding({ left: 35, right: 35, top: 35 })
1758  }
1759}
1760```
1761![](figures/textExample5.png)
1762
1763### 示例6(设置文本自适应和缩放倍数限制范围)
1764
1765该示例通过[heightAdaptivePolicy](#heightadaptivepolicy10)(从API version 10开始)属性展示文本自适应效果以及通过[minFontScale](#minfontscale12)(从API version 12开始)、[maxFontScale](#maxfontscale12)(从API version 12开始)展示设置字体缩放倍数限制范围。
1766
1767```ts
1768// xxx.ets
1769@Extend(Text)
1770function style(HeightAdaptivePolicy: TextHeightAdaptivePolicy) {
1771  .width('80%')
1772  .height(90)
1773  .borderWidth(1)
1774  .minFontSize(10)
1775  .maxFontSize(30)
1776  .maxLines(2)
1777  .margin(5)
1778  .textOverflow({ overflow: TextOverflow.Ellipsis })
1779  .heightAdaptivePolicy(HeightAdaptivePolicy)
1780}
1781
1782@Entry
1783@Component
1784struct TextExample6 {
1785  build() {
1786    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1787      // 设置文本自适应高度的方式
1788      Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC)
1789      Text('This is the text with the height adaptive policy set.')
1790        .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
1791      Text('This is the text with the height adaptive policy set.')
1792        .style(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
1793      Text('This is the text with the height adaptive policy set.')
1794        .style(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)
1795
1796      Text('fontScale').fontSize(9).fontColor(0xCCCCCC)
1797      Text('This is the text content with minFontScale set to 1 and maxFontScale set to 1.2')
1798        .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
1799        .minFontScale(1)
1800        .maxFontScale(1.2)
1801    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1802  }
1803}
1804```
1805
1806![textHeightAdaptivePolicy](figures/textHeightAdaptivePolicy.PNG)
1807
1808### 示例7(设置文本识别)
1809
1810从API version 11开始,该示例通过[enableDataDetector](#enabledatadetector11)、[dataDetectorConfig](#datadetectorconfig11)接口实现了文本识别的功能。
1811
1812```ts
1813// xxx.ets
1814@Entry
1815@Component
1816struct TextExample7 {
1817  @State phoneNumber: string = '(86) (755) ********';
1818  @State url: string = 'www.********.com';
1819  @State email: string = '***@example.com';
1820  @State address: string = 'XX省XX市XX区XXXX';
1821  @State datetime: string = 'XX年XX月XX日XXXX';
1822  @State enableDataDetector: boolean = true;
1823  @State types: TextDataDetectorType[] = [];
1824
1825  build() {
1826    Row() {
1827      Column() {
1828        Text(
1829          '电话号码:' + this.phoneNumber + '\n' +
1830            '链接:' + this.url + '\n' +
1831            '邮箱:' + this.email + '\n' +
1832            '地址:' + this.address + '\n' +
1833            '时间:' + this.datetime
1834        )
1835          .fontSize(16)
1836          .copyOption(CopyOptions.InApp)
1837          .enableDataDetector(this.enableDataDetector)
1838          .dataDetectorConfig({
1839            types: this.types, onDetectResultUpdate: (result: string) => {
1840            }
1841          })
1842          .textAlign(TextAlign.Center)
1843          .borderWidth(1)
1844          .padding(10)
1845          .width('100%')
1846      }
1847      .width('100%')
1848      // 使用parallelGesture中的TapGesture替代onClick属性,达到非冒泡事件类似冒泡
1849      // 的效果,点击Text组件区域Column上的点击事件正常响应
1850      .parallelGesture(TapGesture().onAction((event: GestureEvent) => {
1851        console.info('test column onClick timestamp:' + event.timestamp);
1852      }), GestureMask.Normal)
1853    }
1854    .height('100%')
1855  }
1856}
1857```
1858
1859![](figures/text7.png)
1860
1861### 示例8(文本绑定自定义菜单)
1862
1863从API version 11开始,该示例通过[bindSelectionMenu](#bindselectionmenu11)、[onTextSelectionChange](#ontextselectionchange11)、[closeSelectionMenu](#closeselectionmenu)接口实现了文本绑定自定义菜单的功能。
1864
1865```ts
1866// xxx.ets
1867@Entry
1868@Component
1869struct TextExample8 {
1870  controller: TextController = new TextController();
1871  options: TextOptions = { controller: this.controller };
1872
1873  build() {
1874    Column() {
1875      Column() {
1876        Text(undefined, this.options) {
1877          Span('Hello World')
1878          // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件。
1879          ImageSpan($r('app.media.startIcon'))
1880            .width(50)
1881            .height(50)
1882            .objectFit(ImageFit.Fill)
1883            .verticalAlign(ImageSpanAlignment.CENTER)
1884        }
1885        .copyOption(CopyOptions.InApp)
1886        .bindSelectionMenu(TextSpanType.IMAGE, this.LongPressImageCustomMenu, TextResponseType.LONG_PRESS, {
1887          onDisappear: () => {
1888            console.info(`自定义选择菜单关闭时回调`);
1889          },
1890          onAppear: () => {
1891            console.info(`自定义选择菜单弹出时回调`);
1892          }
1893        })
1894        .bindSelectionMenu(TextSpanType.TEXT, this.RightClickTextCustomMenu, TextResponseType.RIGHT_CLICK)
1895        .bindSelectionMenu(TextSpanType.MIXED, this.SelectMixCustomMenu, TextResponseType.SELECT)
1896        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
1897          console.info(`文本选中区域变化回调, selectionStart: ${selectionStart}, selectionEnd: ${selectionEnd}`);
1898        })
1899        .borderWidth(1)
1900        .borderColor(Color.Red)
1901        .width(200)
1902        .height(100)
1903      }
1904      .width('100%')
1905      .backgroundColor(Color.White)
1906      .alignItems(HorizontalAlign.Start)
1907      .padding(25)
1908    }
1909    .height('100%')
1910  }
1911
1912  @Builder
1913  RightClickTextCustomMenu() {
1914    Column() {
1915      Menu() {
1916        MenuItemGroup() {
1917          // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件。
1918          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Right Click Menu 1", labelInfo: "" })
1919            .onClick((event) => {
1920              this.controller.closeSelectionMenu();
1921            })
1922          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Right Click Menu 2", labelInfo: "" })
1923          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Right Click Menu 3", labelInfo: "" })
1924        }
1925      }
1926      .MenuStyles()
1927    }
1928  }
1929
1930  @Builder
1931  LongPressImageCustomMenu() {
1932    Column() {
1933      Menu() {
1934        MenuItemGroup() {
1935          // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件。
1936          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Long Press Image Menu 1", labelInfo: "" })
1937            .onClick((event) => {
1938              this.controller.closeSelectionMenu();
1939            })
1940          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Long Press Image Menu 2", labelInfo: "" })
1941          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Long Press Image Menu 3", labelInfo: "" })
1942        }
1943      }
1944      .MenuStyles()
1945    }
1946  }
1947
1948  @Builder
1949  SelectMixCustomMenu() {
1950    Column() {
1951      Menu() {
1952        MenuItemGroup() {
1953          // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件。
1954          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Select Mixed Menu 1", labelInfo: "" })
1955            .onClick((event) => {
1956              this.controller.closeSelectionMenu();
1957            })
1958          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Select Mixed Menu 2", labelInfo: "" })
1959          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Select Mixed Menu 3", labelInfo: "" })
1960        }
1961      }
1962      .MenuStyles()
1963    }
1964  }
1965}
1966
1967@Extend(Menu)
1968function MenuStyles() {
1969  .radius($r('sys.float.ohos_id_corner_radius_card'))
1970  .clip(true)
1971  .backgroundColor('#F0F0F0')
1972}
1973```
1974
1975![](figures/textBindSelectionMenu.gif)
1976
1977### 示例9(设置文本特性与行间距)
1978
1979从API version 12开始,该示例通过[fontFeature](#fontfeature12)、[lineSpacing](#linespacing12)接口展示了设置文本特性与行间距的效果,同时,配置[LineSpacingOptions](ts-text-common.md#linespacingoptions20对象说明)中的onlyBetweenLines(从API version 20开始)属性,可以设置文本的行间距,是否仅在行与行之间生效。
1980
1981```ts
1982// xxx.ets
1983import { LengthMetrics } from '@kit.ArkUI';
1984
1985@Extend(Text)
1986function style() {
1987  .fontSize(12)
1988  .border({ width: 1 })
1989  .width('100%')
1990}
1991
1992@Entry
1993@Component
1994struct TextExample9 {
1995  build() {
1996    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
1997      Text('lineSpacing').fontSize(9).fontColor(0xCCCCCC)
1998      // 设置文本行间距
1999      Text('This is a context with no lineSpacing set.')
2000        .lineSpacing(undefined)
2001        .style()
2002      Text('This is a context with lineSpacing set to 20_px.')
2003        .lineSpacing(LengthMetrics.px(20))
2004        .style()
2005      Text('This is the context with lineSpacing set to 20_vp.')
2006        .lineSpacing(LengthMetrics.vp(20))
2007        .style()
2008      Text('This is the context with lineSpacing set to 20_fp.')
2009        .lineSpacing(LengthMetrics.fp(20))
2010        .style()
2011      Text('This is the context with lineSpacing set to 20_lpx.')
2012        .lineSpacing(LengthMetrics.lpx(20))
2013        .style()
2014      Text('This is the context with lineSpacing set to 100%.')
2015        .lineSpacing(LengthMetrics.percent(1))
2016        .style()
2017      Text('The line spacing of this context is set to 20_px, and the spacing is effective only between the lines.')
2018        .lineSpacing(LengthMetrics.px(20), { onlyBetweenLines: true })
2019        .style()
2020
2021      Text('fontFeature').fontSize(9).fontColor(0xCCCCCC)
2022      // 设置文本特性
2023      Text('This is ss01 on : 0123456789')
2024        .fontFeature("\"ss01\" on")
2025        .style()
2026      Text('This is ss01 off: 0123456789')
2027        .fontFeature("\"ss01\" off")
2028        .style()
2029    }.height(300).width(350).padding({ left: 35, right: 35, top: 35 })
2030  }
2031}
2032```
2033
2034![](figures/TextExample8.PNG)
2035
2036### 示例10(获取文本信息)
2037
2038从API version 12开始,该示例通过[getLayoutManager](#getlayoutmanager12)接口调用文本的布局管理对象获取文本信息,同时,[LayoutManager](ts-text-common.md#layoutmanager12)中的[getRectsForRange](./ts-text-common.md#getrectsforrange14)(从API version 14开始)接口可以获取指定矩形宽度和高度下,文本中任意区间范围内字符或占位符的绘制区域信息。
2039
2040```ts
2041// xxx.ets
2042import { text } from '@kit.ArkGraphics2D';
2043
2044@Entry
2045@Component
2046struct TextExample10 {
2047  @State lineCount: string = "";
2048  @State glyphPositionAtCoordinate: string = "";
2049  @State lineMetrics: string = "";
2050  @State rectsForRangeStr: string = "";
2051  controller: TextController = new TextController();
2052  @State textStr: string =
2053    'Hello World! 您好,世界!';
2054
2055  build() {
2056    Scroll() {
2057      Column() {
2058        Text('Text组件getLayoutManager接口获取段落相对组件的信息')
2059          .fontSize(15)
2060          .fontColor(0xCCCCCC)
2061          .width('90%')
2062          .padding(10)
2063        Text(this.textStr, { controller: this.controller })
2064          .fontSize(25)
2065          .borderWidth(1)
2066          .onAreaChange(() => {
2067            let layoutManager: LayoutManager = this.controller.getLayoutManager();
2068            this.lineCount = "LineCount: " + layoutManager.getLineCount();
2069          })
2070
2071        Text('LineCount').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
2072        Text(this.lineCount)
2073
2074        Text('GlyphPositionAtCoordinate').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
2075        Button("相对组件坐标[150,50]字形信息")
2076          .onClick(() => {
2077            let layoutManager: LayoutManager = this.controller.getLayoutManager();
2078            let position: PositionWithAffinity = layoutManager.getGlyphPositionAtCoordinate(150, 50);
2079            this.glyphPositionAtCoordinate =
2080              "相对组件坐标[150,50] glyphPositionAtCoordinate position: " + position.position + " affinity: " +
2081              position.affinity;
2082          })
2083          .margin({ bottom: 20, top: 10 })
2084        Text(this.glyphPositionAtCoordinate)
2085
2086        Text('LineMetrics').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
2087        Button("首行行信息、文本样式信息、以及字体属性信息")
2088          .onClick(() => {
2089            let layoutManager: LayoutManager = this.controller.getLayoutManager();
2090            let lineMetrics: LineMetrics = layoutManager.getLineMetrics(0);
2091            this.lineMetrics = "lineMetrics is " + JSON.stringify(lineMetrics) + "\n\n";
2092            let runMetrics = lineMetrics.runMetrics;
2093            runMetrics.forEach((value, key) => {
2094              this.lineMetrics += "runMetrics key is " + key + " " + JSON.stringify(value) + "\n\n";
2095            })
2096          })
2097          .margin({ bottom: 20, top: 10 })
2098        Text(this.lineMetrics)
2099
2100        Text('getRectsForRange').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
2101        Button("获取指定矩形宽度和高度下,文本中任意区间范围内字符或占位符的绘制区域信息")
2102          .onClick(() => {
2103            let layoutManager: LayoutManager = this.controller.getLayoutManager();
2104            let range: TextRange = { start: 0, end: 1 };
2105            let rectsForRangeInfo: text.TextBox[] =
2106              layoutManager.getRectsForRange(range, text.RectWidthStyle.TIGHT, text.RectHeightStyle.TIGHT);
2107            this.rectsForRangeStr = "getRectsForRange result is " + "\n\n";
2108            rectsForRangeInfo.forEach((value, key) => {
2109              this.rectsForRangeStr += "rectsForRange key is " + key + " " + JSON.stringify(value) + "\n\n";
2110            })
2111          })
2112          .margin({ bottom: 20, top: 10 })
2113        Text(this.rectsForRangeStr)
2114      }
2115      .margin({ top: 100, left: 8, right: 8 })
2116    }
2117  }
2118}
2119```
2120
2121![textLayoutManager](figures/textLayoutManager.gif)
2122
2123### 示例11(实现键盘框选文本)
2124
2125从API version 12开始,该示例通过[textSelectable](#textselectable12)属性实现了设置TextSelectMode.SELECTABLE_FOCUSABLE时能够触发键盘框选文本功能。
2126
2127```ts
2128// xxx.ets
2129@Entry
2130@Component
2131struct TextExample11 {
2132  @State message: string =
2133    'TextTextTextTextTextTextTextText' + 'TextTextTextTextTextTextTextTextTextTextTextTextTextTextTextText';
2134
2135  build() {
2136    Column() {
2137      Text(this.message)
2138        .width(300)
2139        .height(100)
2140        .maxLines(5)
2141        .fontColor(Color.Black)
2142        .copyOption(CopyOptions.InApp)
2143        .selection(3, 8)
2144        .textSelectable(TextSelectableMode.SELECTABLE_FOCUSABLE)
2145    }.width('100%').margin({ top: 100 })
2146  }
2147}
2148```
2149
2150![textTextSelectableMode](figures/textTextSelectableMode.gif)
2151
2152### 示例12(文本扩展自定义菜单)
2153
2154从API version 12开始,该示例通过[editMenuOptions](#editmenuoptions12)接口实现了文本设置自定义菜单扩展项的文本内容、图标以及回调的功能,同时,可以在[onPrepareMenu](ts-text-common.md#onpreparemenu20)(从API version 20开始)回调中,进行菜单数据的设置。
2155
2156```ts
2157// xxx.ets
2158@Entry
2159@Component
2160struct TextExample12 {
2161  @State text: string = 'Text editMenuOptions'
2162  @State endIndex: number = 0;
2163  onCreateMenu = (menuItems: Array<TextMenuItem>) => {
2164    // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件。
2165    let item1: TextMenuItem = {
2166      content: 'create1',
2167      icon: $r('app.media.startIcon'),
2168      id: TextMenuItemId.of('create1'),
2169    };
2170    let item2: TextMenuItem = {
2171      content: 'create2',
2172      id: TextMenuItemId.of('create2'),
2173      icon: $r('app.media.startIcon'),
2174    };
2175    menuItems.push(item1);
2176    menuItems.unshift(item2);
2177    return menuItems;
2178  }
2179  onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange) => {
2180    if (menuItem.id.equals(TextMenuItemId.of("create2"))) {
2181      console.info("拦截 id: create2 start:" + textRange.start + "; end:" + textRange.end);
2182      return true;
2183    }
2184    if (menuItem.id.equals(TextMenuItemId.of("prepare1"))) {
2185      console.info("拦截 id: prepare1 start:" + textRange.start + "; end:" + textRange.end);
2186      return true;
2187    }
2188    if (menuItem.id.equals(TextMenuItemId.COPY)) {
2189      console.info("拦截 COPY start:" + textRange.start + "; end:" + textRange.end);
2190      return true;
2191    }
2192    if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
2193      console.info("不拦截 SELECT_ALL start:" + textRange.start + "; end:" + textRange.end);
2194      return false;
2195    }
2196    return false;
2197  }
2198  // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件。
2199  onPrepareMenu = (menuItems: Array<TextMenuItem>) => {
2200    let item1: TextMenuItem = {
2201      content: 'prepare1_' + this.endIndex,
2202      icon: $r('app.media.startIcon'),
2203      id: TextMenuItemId.of('prepare1'),
2204    };
2205    menuItems.unshift(item1);
2206    return menuItems;
2207  }
2208  @State editMenuOptions: EditMenuOptions = {
2209    onCreateMenu: this.onCreateMenu,
2210    onMenuItemClick: this.onMenuItemClick,
2211    onPrepareMenu: this.onPrepareMenu
2212  };
2213
2214  build() {
2215    Column() {
2216      Text(this.text)
2217        .fontSize(20)
2218        .copyOption(CopyOptions.LocalDevice)
2219        .editMenuOptions(this.editMenuOptions)
2220        .margin({ top: 100 })
2221        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
2222          this.endIndex = selectionEnd;
2223        })
2224    }
2225    .width("90%")
2226    .margin("5%")
2227  }
2228}
2229```
2230
2231![textEditMenuOptions](figures/textEditMenuOptions.gif)
2232
2233### 示例13(配置隐私隐藏)
2234
2235从API version 12开始,该示例通过[privacySensitive](#privacysensitive12)属性展示了文本如何配置隐私隐藏的效果,实际显示需要卡片框架支持。
2236
2237```ts
2238// xxx.ets
2239@Entry
2240@Component
2241struct TextExample13 {
2242  build() {
2243    Column({ space: 10 }) {
2244      Text("privacySensitive")
2245        .privacySensitive(true)
2246        .margin({ top: 30 })
2247    }
2248    .alignItems(HorizontalAlign.Center)
2249    .width("100%")
2250  }
2251}
2252```
2253
2254![textPrivacySensitive](figures/textPrivacySensitive.gif)
2255
2256### 示例14(设置中西文自动间距)
2257
2258从API version 20开始,该示例通过[enableAutoSpacing](#enableautospacing20)属性设置中西文自动间距。
2259
2260```ts
2261// xxx.ets
2262@Entry
2263@Component
2264struct TextExample {
2265  build() {
2266    Row() {
2267      Column() {
2268        Text('开启中西文自动间距').margin(5)
2269        Text('中西文Auto Spacing自动间距')
2270          .enableAutoSpacing(true)
2271        Text('关闭中西文自动间距').margin(5)
2272        Text('中西文Auto Spacing自动间距')
2273          .enableAutoSpacing(false)
2274      }.height('100%')
2275    }
2276    .width('60%')
2277  }
2278}
2279```
2280
2281![textEnableAutoSpacing](figures/textEnableAutoSpacing.png)
2282
2283### 示例15(文本颜色按线性或径向渐变)
2284
2285从API version 20开始,该示例通过[shaderStyle](#shaderstyle20)接口实现了对Text组件显示为渐变色和纯色的功能。
2286
2287```ts
2288@Entry
2289@Component
2290struct ShaderColorStyle {
2291  @State message: string = 'Hello World';
2292  @State linearGradientOptions1: LinearGradientOptions =
2293    {
2294      angle: 45,
2295      colors: [[Color.Red, 0.0], [Color.Blue, 0.3], [Color.Green, 0.5]]
2296    };
2297  @State linearGradientOptions2: LinearGradientOptions =
2298    {
2299      direction: GradientDirection.LeftTop,
2300      colors: [[Color.Red, 0.0], [Color.Blue, 0.3], [Color.Green, 0.5]],
2301      repeating: true,
2302    };
2303  @State radialGradientOptions: RadialGradientOptions =
2304    {
2305      center: [50, 50],
2306      radius: 20,
2307      colors: [[Color.Red, 0.0], [Color.Blue, 0.3], [Color.Green, 0.5]],
2308      repeating: true,
2309    };
2310  @State colorShaderStyle: ColorShaderStyle =
2311    {
2312      color: Color.Blue
2313    };
2314  build() {
2315    Column({ space: 5 }) {
2316      Text('angle为45°的线性渐变').fontSize(18).width('90%').fontColor(0xCCCCCC)
2317        .margin({ top: 40, left: 40 })
2318      Text(this.message)
2319        .fontSize(50)
2320        .width('80%')
2321        .height(50)
2322        .shaderStyle(this.linearGradientOptions1)
2323      Text('direction为LeftTop的线性渐变').fontSize(18).width('90%').fontColor(0xCCCCCC)
2324        .margin({ top: 40, left: 40 })
2325      Text(this.message)
2326        .fontSize(50)
2327        .width('80%')
2328        .height(50)
2329        .shaderStyle(this.linearGradientOptions2)
2330      Text('径向渐变').fontSize(18).width('90%').fontColor(0xCCCCCC)
2331        .margin({ top: 40, left: 40 })
2332      Text(this.message)
2333        .fontSize(50)
2334        .width('80%')
2335        .height(50)
2336        .shaderStyle(this.radialGradientOptions)
2337      Text('纯色').fontSize(18).width('90%').fontColor(0xCCCCCC)
2338        .margin({ top: 40, left: 40 })
2339      Text(this.message)
2340        .fontSize(50)
2341        .width('80%')
2342        .height(50)
2343        .shaderStyle(this.colorShaderStyle)
2344    }
2345  }
2346}
2347```
2348![zh-cn_image_0000001219864149](figures/gradientcolor.png)
2349
2350### 示例16(配置除去行尾空格)
2351
2352从API version 20开始,该示例通过[optimizeTrailingSpace](#optimizetrailingspace20)属性展示了文本如何配置除去行尾空格的效果,一般需要与对齐功能搭配使用,实际显示需要字体引擎支持。
2353
2354```ts
2355// xxx.ets
2356@Entry
2357@Component
2358struct TextExample16 {
2359  build() {
2360    Column() {
2361      Text("Trimmed space enabled     ")
2362        .fontSize(30)
2363        .fontWeight(FontWeight.Bold)
2364        .margin({ top: 20 })
2365        .optimizeTrailingSpace(true)
2366        .textAlign(TextAlign.Center)
2367      Text("Trimmed space disabled     ")
2368        .fontSize(30)
2369        .fontWeight(FontWeight.Bold)
2370        .margin({ top: 20 })
2371        .optimizeTrailingSpace(false)
2372        .textAlign(TextAlign.Center)
2373    }
2374    .width("100%")
2375  }
2376}
2377```
2378
2379![textOptimizeTrailingSpace](figures/textOptimizeTrailingSpace.PNG)
2380
2381### 示例17(文本垂直对齐)
2382
2383从API version 20开始,该示例通过[textVerticalAlign](#textverticalalign20)属性展示了文本如何设置文本垂直对齐效果。
2384
2385```ts
2386// xxx.ets
2387@Entry
2388@Component
2389struct TextExample14 {
2390  build() {
2391    Column({ space: 10 }) {
2392      Text() {
2393        Span("Hello")
2394          .fontSize(50)
2395        // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件。
2396        ImageSpan($r('app.media.startIcon'))
2397          .width(30).height(30)
2398          .verticalAlign(ImageSpanAlignment.FOLLOW_PARAGRAPH)// 从API version 20开始,支持ImageSpanAlignment.FOLLOW_PARAGRAPH
2399        Span("World")
2400      }
2401      .textVerticalAlign(TextVerticalAlign.CENTER)
2402      .borderWidth(1)
2403    }
2404    .alignItems(HorizontalAlign.Center)
2405    .width("100%")
2406  }
2407}
2408```
2409
2410![textVerticalAlign](figures/textVerticalAlign.png)
2411
2412### 示例18(文本翻牌动效)
2413
2414从API version 20开始,该示例通过[contentTransition](#contenttransition20)属性展示了数字翻牌效果。
2415
2416```ts
2417// xxx.ets
2418@Entry
2419@Component
2420struct TextNumberTransition {
2421  @State number: number = 98;
2422  @State numberTransition: NumericTextTransition = new NumericTextTransition({ flipDirection: FlipDirection.DOWN, enableBlur: false });
2423
2424  build() {
2425    Column() {
2426      Text(this.number + "")
2427        .borderWidth(1)
2428        .fontSize(40)
2429        .contentTransition(this.numberTransition)
2430      Button("chang number")
2431        .onClick(() => {
2432          this.number++;
2433        })
2434        .margin(10)
2435    }
2436    .height('100%')
2437    .width('100%')
2438  }
2439}
2440```
2441
2442![Text_content_transition](figures/Text_content_transition.gif)