1# Text
2
3显示一段文本的组件。
4
5>  **说明:**
6>
7>  该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
8
9
10## 子组件
11
12可以包含[Span](ts-basic-components-span.md)、[ImageSpan](ts-basic-components-imagespan.md)、[SymbolSpan](ts-basic-components-symbolSpan.md)和[ContainerSpan](ts-basic-components-containerspan.md)子组件。
13
14## 接口
15
16Text(content?: string | Resource , value?: TextOptions)
17
18**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
19
20**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
21
22**系统能力:** SystemCapability.ArkUI.ArkUI.Full
23
24**参数:**
25
26| 参数名 | 类型 | 必填 | 说明 |
27| -------- | -------- | -------- | -------- |
28| content | string \| [Resource](ts-types.md#resource) | 否 | 文本内容。包含子组件Span且未设置[属性字符串](ts-universal-styled-string.md#属性字符串)时不生效,显示Span内容,并且此时text组件的样式不生效。<br/>默认值:' ' |
29| value<sup>11+</sup> | [TextOptions](#textoptions11) | 否 | 文本组件初始化选项。|
30
31## 属性
32
33除支持[通用属性](ts-universal-attributes-size.md),还支持以下属性:
34
35### textAlign
36
37textAlign(value: TextAlign)
38
39设置文本段落在水平方向的对齐方式。
40
41文本段落宽度占满Text组件宽度。
42
43可通过[align](ts-universal-attributes-location.md)属性控制文本段落在垂直方向上的位置,此组件中不可通过align属性控制文本段落在水平方向上的位置,即align属性中Alignment.TopStartAlignment.TopAlignment.TopEnd效果相同,控制内容在顶部,Alignment.StartAlignment.CenterAlignment.End效果相同,控制内容垂直居中,Alignment.BottomStartAlignment.BottomAlignment.BottomEnd效果相同,控制内容在底部。结合TextAlign属性可控制内容在水平方向的位置。
44
45当textAlign属性设置为TextAlign.JUSTIFY时,需要根据文本内容设置[wordBreak](#wordbreak11)属性,且最后一行文本不参与两端对齐,为水平对齐首部效果。
46
47**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
48
49**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
50
51**系统能力:** SystemCapability.ArkUI.ArkUI.Full
52
53**参数:** 
54
55| 参数名 | 类型                                        | 必填 | 说明                                                       |
56| ------ | ------------------------------------------- | ---- | ---------------------------------------------------------- |
57| value  | [TextAlign](ts-appendix-enums.md#textalign) | 是   | 文本段落在水平方向的对齐方式。<br/>默认值:TextAlign.Start |
58
59### textOverflow
60
61textOverflow(value: { overflow: TextOverflow })
62
63设置文本超长时的显示方式。
64
65文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。从API version 11开始,建议优先组合wordBreak属性设置为WordBreak.BREAK_ALL方式实现字母为单位进行截断,使用[示例](#示例4)。
66
67当overflow设置为TextOverflow.NoneTextOverflow.ClipTextOverflow.Ellipsis时,需配合maxLines使用,单独设置不生效。设置TextOverflow.NoneTextOverflow.Clip效果一样。
68
69当overflow设置为TextOverflow.MARQUEE时,文本在一行内滚动显示,设置maxLines及copyOption属性均不生效。在文本不可滚动时,设置textAlign属性生效;在文本可滚动时,设置textAlign属性不生效。在跑马灯模式下,Text组件clip属性默认为true。属性字符串的[CustomSpan](ts-universal-styled-string.md#customspan)不支持跑马灯模式。
70
71从API version 12开始,当overflow设置为TextOverflow.MARQUEE时,支持ImageSpan组件,文本和图片在一行内滚动显示。
72
73**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
74
75**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
76
77**系统能力:** SystemCapability.ArkUI.ArkUI.Full
78
79**参数:** 
80
81| 参数名 | 类型                                                         | 必填 | 说明                                                         |
82| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
83| value  | {overflow:&nbsp;[TextOverflow](ts-appendix-enums.md#textoverflow)} | 是   | 文本超长时的显示方式。<br/>默认值:{overflow:&nbsp;TextOverflow.Clip} |
84
85### maxLines
86
87maxLines(value: number)
88
89设置文本的最大行数。默认情况下,文本是自动折行的,如果指定此属性,则文本最多不会超过指定的行。如果有多余的文本,可以通过[textOverflow](#textoverflow)来指定截断方式。
90
91**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
92
93**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
94
95**系统能力:** SystemCapability.ArkUI.ArkUI.Full
96
97**参数:** 
98
99| 参数名 | 类型   | 必填 | 说明             |
100| ------ | ------ | ---- | ---------------- |
101| value  | number | 是   | 文本的最大行数。 |
102
103### lineHeight
104
105lineHeight(value: number | string | Resource)
106
107设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,number类型时单位为fp。
108
109**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
110
111**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
112
113**系统能力:** SystemCapability.ArkUI.ArkUI.Full
114
115**参数:** 
116
117| 参数名 | 类型                                                         | 必填 | 说明             |
118| ------ | ------------------------------------------------------------ | ---- | ---------------- |
119| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 文本的文本行高。 |
120
121### decoration
122
123decoration(value: DecorationStyleInterface)
124
125设置文本装饰线样式及其颜色。
126
127**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
128
129**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
130
131**系统能力:** SystemCapability.ArkUI.ArkUI.Full
132
133**参数:** 
134
135| 参数名 | 类型                                                         | 必填 | 说明                                                         |
136| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
137| 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参数不支持卡片能力。 |
138
139### baselineOffset
140
141baselineOffset(value: number | string)
142
143设置文本基线的偏移量,设置该值为百分比时,按默认值显示。
144
145正数内容向上偏移,负数向下偏移。
146
147**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
148
149**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
150
151**系统能力:** SystemCapability.ArkUI.ArkUI.Full
152
153**参数:** 
154
155| 参数名 | 类型                       | 必填 | 说明                             |
156| ------ | -------------------------- | ---- | -------------------------------- |
157| value  | number&nbsp;\|&nbsp;string | 是   | 文本基线的偏移量。<br/>默认值:0 |
158
159### letterSpacing
160
161letterSpacing(value: number | string)
162
163设置文本字符间距。设置该值为百分比时,按默认值显示。设置该值为0时,按默认值显示。
164
165当取值为负值时,文字会发生压缩,负值过小时会将组件内容区大小压缩为0,导致无内容显示。
166
167**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
168
169**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
170
171**系统能力:** SystemCapability.ArkUI.ArkUI.Full
172
173**参数:** 
174
175| 参数名 | 类型                       | 必填 | 说明           |
176| ------ | -------------------------- | ---- | -------------- |
177| value  | number&nbsp;\|&nbsp;string | 是   | 文本字符间距。 |
178
179### minFontSize
180
181minFontSize(value: number | string | Resource)
182
183设置文本最小显示字号。
184
185需配合[maxFontSize](#maxfontsize)以及[maxlines](#maxlines)或布局大小限制使用,单独设置不生效,对子组件和属性字符串不生效。
186
187自适应字号生效时,fontSize设置不生效。
188
189minFontSize小于或等于0时,自适应字号不生效。
190
191**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
192
193**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
194
195**系统能力:** SystemCapability.ArkUI.ArkUI.Full
196
197**参数:** 
198
199| 参数名 | 类型                                                         | 必填 | 说明               |
200| ------ | ------------------------------------------------------------ | ---- | ------------------ |
201| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 文本最小显示字号。 |
202
203### maxFontSize
204
205maxFontSize(value: number | string | Resource)
206
207设置文本最大显示字号。
208
209需配合[minFontSize](#minfontsize)以及[maxlines](#maxlines)或布局大小限制使用,单独设置不生效,对子组件和属性字符串不生效。
210
211自适应字号生效时,fontSize设置不生效。
212
213**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
214
215**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
216
217**系统能力:** SystemCapability.ArkUI.ArkUI.Full
218
219**参数:** 
220
221| 参数名 | 类型                                                         | 必填 | 说明               |
222| ------ | ------------------------------------------------------------ | ---- | ------------------ |
223| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 文本最大显示字号。 |
224
225### textCase
226
227textCase(value: TextCase)
228
229设置文本大小写。
230
231**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
232
233**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
234
235**系统能力:** SystemCapability.ArkUI.ArkUI.Full
236
237**参数:** 
238
239| 参数名 | 类型                                      | 必填 | 说明                                      |
240| ------ | ----------------------------------------- | ---- | ----------------------------------------- |
241| value  | [TextCase](ts-appendix-enums.md#textcase) | 是   | 文本大小写。<br />默认值:TextCase.Normal |
242
243### fontColor
244
245fontColor(value: ResourceColor)
246
247设置字体颜色。
248
249**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
250
251**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
252
253**系统能力:** SystemCapability.ArkUI.ArkUI.Full
254
255**参数:** 
256
257| 参数名 | 类型                                       | 必填 | 说明       |
258| ------ | ------------------------------------------ | ---- | ---------- |
259| value  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 字体颜色。 |
260
261### fontSize
262
263fontSize(value: number | string | Resource)
264
265设置字体大小。
266
267**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
268
269**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
270
271**系统能力:** SystemCapability.ArkUI.ArkUI.Full
272
273**参数:** 
274
275| 参数名 | 类型                                                         | 必填 | 说明                                                         |
276| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
277| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 字体大小。fontSize为number类型时,使用fp单位。字体默认大小16fp。不支持设置百分比字符串。 |
278
279### fontStyle
280
281fontStyle(value: FontStyle)
282
283设置字体样式。
284
285**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
286
287**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
288
289**系统能力:** SystemCapability.ArkUI.ArkUI.Full
290
291**参数:** 
292
293| 参数名 | 类型                                        | 必填 | 说明                                    |
294| ------ | ------------------------------------------- | ---- | --------------------------------------- |
295| value  | [FontStyle](ts-appendix-enums.md#fontstyle) | 是   | 字体样式。<br/>默认值:FontStyle.Normal |
296
297### fontWeight
298
299fontWeight(value: number | FontWeight | string)
300
301设置文本的字体粗细,设置过大可能会在不同字体下有截断。
302
303**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
304
305**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
306
307**系统能力:** SystemCapability.ArkUI.ArkUI.Full
308
309**参数:** 
310
311| 参数名 | 类型                                                         | 必填 | 说明                                                         |
312| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
313| value  | number&nbsp;\|&nbsp;[FontWeight](ts-appendix-enums.md#fontweight)&nbsp;\|&nbsp;string | 是   | 文本的字体粗细,number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。<br/>默认值:FontWeight.Normal |
314
315### fontFamily
316
317fontFamily(value: string | Resource)
318
319设置字体列表。
320
321**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
322
323**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
324
325**系统能力:** SystemCapability.ArkUI.ArkUI.Full
326
327**参数:** 
328
329| 参数名 | 类型                                                 | 必填 | 说明                                                         |
330| ------ | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
331| value  | string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 字体列表。默认字体'HarmonyOS Sans'。<br>应用当前支持'HarmonyOS Sans'字体和[注册自定义字体](../js-apis-font.md)。<br>卡片当前仅支持'HarmonyOS Sans'字体。 |
332
333### copyOption<sup>9+</sup>
334
335copyOption(value: CopyOptions)
336
337设置组件是否支持文本可复制粘贴。设置copyOptions为CopyOptions.InApp或者CopyOptions.LocalDevice,长按文本,会弹出文本选择菜单,可选中文本并进行复制、全选操作。
338
339由于卡片没有长按事件,此场景下长按文本,不会弹出文本选择菜单。
340
341**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
342
343**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
344
345**系统能力:** SystemCapability.ArkUI.ArkUI.Full
346
347**参数:** 
348
349| 参数名 | 类型                                             | 必填 | 说明                                                       |
350| ------ | ------------------------------------------------ | ---- | ---------------------------------------------------------- |
351| value  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 是   | 组件是否支持文本可复制粘贴。<br />默认值:CopyOptions.None |
352
353### draggable<sup>9+</sup>
354
355draggable(value: boolean)
356
357设置选中文本拖拽效果。
358
359不能和[onDragStart](ts-universal-events-drag-drop.md)事件同时使用。
360
361需配合[CopyOptions](ts-appendix-enums.md#copyoptions9)一起使用,设置copyOptions为CopyOptions.InApp或者CopyOptions.LocalDevice,并且draggable设置为true时,支持对选中文本的拖拽以及选中内容复制到输入框。
362
363**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
364
365**系统能力:** SystemCapability.ArkUI.ArkUI.Full
366
367**参数:** 
368
369| 参数名 | 类型    | 必填 | 说明                                 |
370| ------ | ------- | ---- | ------------------------------------ |
371| value  | boolean | 是   | 选中文本拖拽效果。<br/>默认值:false |
372
373### font<sup>10+</sup>
374
375font(value: Font)
376
377设置文本样式。包括字体大小、字体粗细、字体族和字体风格。
378
379**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
380
381**系统能力:** SystemCapability.ArkUI.ArkUI.Full
382
383**参数:** 
384
385| 参数名 | 类型    | 必填 | 说明       |
386| ------ | ------- | ---- | ---------- |
387| value  | [Font](ts-types.md#font) | 是   | 文本样式。 |
388
389### textShadow<sup>10+</sup>
390
391textShadow(value: ShadowOptions | Array&lt;ShadowOptions&gt;)
392
393设置文字阴影效果。
394
395不支持fill字段,不支持智能取色模式。
396
397从API version 11开始,该接口支持以数组形式入参,实现多重文字阴影。
398
399**卡片能力:** 从API version 10开始,该接口支持在ArkTS卡片中使用。
400
401**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
402
403**系统能力:** SystemCapability.ArkUI.ArkUI.Full
404
405**参数:** 
406
407| 参数名 | 类型                                                         | 必填 | 说明           |
408| ------ | ------------------------------------------------------------ | ---- | -------------- |
409| 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> | 是   | 文字阴影效果。 |
410
411### heightAdaptivePolicy<sup>10+</sup>
412
413heightAdaptivePolicy(value: TextHeightAdaptivePolicy)
414
415设置文本自适应高度的方式。
416
417当设置为TextHeightAdaptivePolicy.MAX_LINES_FIRST时,优先使用[maxlines](#maxlines)属性来调整文本高度。如果使用maxLines属性的布局大小超过了布局约束,则尝试在[minFontSize](#minfontsize)和[maxFontSize](#maxfontsize)的范围内缩小字体以显示更多文本。
418
419当设置为TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST时,优先使用minFontSize属性来调整文本高度。如果使用minFontSize属性可以将文本布局在一行中,则尝试在minFontSize和maxFontSize的范围内增大字体并使用最大可能的字体大小。
420
421当设置为TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST时,优先使用布局约束来调整文本高度。如果布局大小超过布局约束,则尝试在minFontSize和maxFontSize的范围内缩小字体以满足布局约束。如果将字体大小缩小到minFontSize后,布局大小仍然超过布局约束,则删除超过布局约束的行。
422
423**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
424
425**系统能力:** SystemCapability.ArkUI.ArkUI.Full
426
427**参数:** 
428
429| 参数名 | 类型                                                         | 必填 | 说明                                                         |
430| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
431| value  | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | 是   | 文本自适应高度的方式。<br/>默认值:TextHeightAdaptivePolicy.MAX_LINES_FIRST |
432
433### textIndent<sup>10+</sup>
434
435textIndent(value: Length)
436
437设置首行文本缩进。
438
439**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
440
441**系统能力:** SystemCapability.ArkUI.ArkUI.Full
442
443**参数:** 
444
445| 参数名 | 类型                         | 必填 | 说明                         |
446| ------ | ---------------------------- | ---- | ---------------------------- |
447| value  | [Length](ts-types.md#length) | 是   | 首行文本缩进。<br/>默认值:0 |
448
449### wordBreak<sup>11+</sup>
450
451wordBreak(value: WordBreak)
452
453设置断行规则。WordBreak.BREAK_ALL与{overflow:&nbsp;TextOverflow.Ellipsis},maxLines组合使用可实现英文单词按字母截断,超出部分以省略号显示
454
455**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
456
457**系统能力:** SystemCapability.ArkUI.ArkUI.Full
458
459**参数:** 
460
461| 参数名 | 类型                                          | 必填 | 说明                                          |
462| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
463| value  | [WordBreak](ts-appendix-enums.md#wordbreak11) | 是   | 断行规则。 <br />默认值:WordBreak.BREAK_WORD |
464
465### selection<sup>11+</sup>
466
467selection(selectionStart: number, selectionEnd: number)
468
469设置选中区域。选中区域高亮且显示手柄和文本选择菜单。
470
471当copyOption设置为CopyOptions.None时,设置selection属性不生效。
472
473当overflow设置为TextOverflow.MARQUEE时,设置selection属性不生效。
474
475当selectionStart大于等于selectionEnd时不选中。可选范围为[0, textSize],textSize为文本内容最大字符数,入参小于0处理为0,大于textSize处理为textSize。
476
477当selectionStart或selectionEnd在截断不可见区域时不选中。截断为false时超出父组件的文本选中区域生效。
478
479**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
480
481**系统能力:** SystemCapability.ArkUI.ArkUI.Full
482
483**参数:** 
484
485| 参数名         | 类型   | 必填 | 说明                                 |
486| -------------- | ------ | ---- | ------------------------------------ |
487| selectionStart | number | 是   | 所选文本的起始位置。<br />默认值:-1 |
488| selectionEnd   | number | 是   | 所选文本的结束位置。<br />默认值:-1 |
489
490### ellipsisMode<sup>11+</sup>
491
492ellipsisMode(value: EllipsisMode)
493
494设置省略位置。ellipsisMode属性需要配合overflow设置为TextOverflow.Ellipsis以及maxLines使用,单独设置ellipsisMode属性不生效。
495
496EllipsisMode.STARTEllipsisMode.CENTER仅在单行超长文本生效。
497
498**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
499
500**系统能力:** SystemCapability.ArkUI.ArkUI.Full
501
502**参数:** 
503
504| 参数名 | 类型                                                | 必填 | 说明                                      |
505| ------ | --------------------------------------------------- | ---- | ----------------------------------------- |
506| value  | [EllipsisMode](ts-appendix-enums.md#ellipsismode11) | 是   | 省略位置。 <br />默认值:EllipsisMode.END |
507
508### enableDataDetector<sup>11+</sup>
509
510enableDataDetector(enable: boolean)
511
512设置是否进行文本特殊实体识别。
513
514该接口依赖设备底层应具有文本识别能力,否则设置不会生效。
515
516当enableDataDetector设置为true,同时不设置dataDetectorConfig属性时,默认识别所有类型的实体,所识别实体的color和decoration会被更改为如下样式:
517
518```ts
519color: '#ff007dff'
520decoration:{
521  type: TextDecorationType.Underline,
522  color: '#ff007dff',
523  style: TextDecorationStyle.SOLID
524}
525```
526
527触摸点击和鼠标右键点击实体,会根据实体类型弹出对应的实体操作菜单,鼠标左键点击实体会直接响应菜单的第一个选项。
528
529当overflow设置为TextOverflow.MARQUEE时,该功能不会生效。
530
531当copyOption设置为CopyOptions.None时,点击实体弹出的菜单没有选择文本和复制功能。当copyOption不为CopyOptions.None,且textSelectable设置为TextSelectableMode.UNSELECTABLE时,仍然具有实体复制功能,但没有选择文本功能。
532
533**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
534
535**系统能力:** SystemCapability.ArkUI.ArkUI.Full
536
537**参数:** 
538
539| 参数名 | 类型    | 必填 | 说明                              |
540| ------ | ------- | ---- | --------------------------------- |
541| enable  | boolean | 是   | 使能文本识别。<br/>默认值: false |
542
543### dataDetectorConfig<sup>11+</sup>
544
545dataDetectorConfig(config: TextDataDetectorConfig)
546
547设置文本识别配置。
548
549需配合[enableDataDetector](#enabledatadetector11)一起使用,设置enableDataDetector为true时,dataDetectorConfig的配置才能生效。
550
551当有两个实体A、B重叠时,按以下规则保留实体:
552
5531.&nbsp;若A&nbsp;⊂&nbsp;B,则保留B,反之则保留A。
554
5552.&nbsp;当A&nbsp;⊄&nbsp;B且B&nbsp;⊄&nbsp;A时,若A.start&nbsp;<&nbsp;B.start,则保留A,反之则保留B。
556
557**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
558
559**系统能力:** SystemCapability.ArkUI.ArkUI.Full
560
561**参数:** 
562
563| 参数名 | 类型                                                        | 必填 | 说明                                                         |
564| ------ | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
565| config | [TextDataDetectorConfig](ts-text-common.md#textdatadetectorconfig11对象说明) | 是   | 文本识别配置。|
566
567### bindSelectionMenu<sup>11+</sup>
568
569bindSelectionMenu(spanType: TextSpanType, content: CustomBuilder, responseType: TextResponseType,
570    options?: SelectionMenuOptions)
571
572设置自定义选择菜单。
573
574bindSelectionMenu长按响应时长为600ms,bindContextMenu长按响应时长为800ms,同时绑定且触发方式均为长按时,优先响应bindSelectionMenu。
575
576自定义菜单超长时,建议内部嵌套[Scroll](./ts-container-scroll.md)组件使用,避免键盘被遮挡。
577
578**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
579
580**系统能力:** SystemCapability.ArkUI.ArkUI.Full
581
582**参数:** 
583
584| 参数名       | 类型                                                         | 必填 | 说明                                                         |
585| ------------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
586| spanType     | [TextSpanType](#textspantype11枚举说明)          | 是   | 选择菜单的类型。<br/>默认值:TextSpanType.TEXT               |
587| content      | [CustomBuilder](ts-types.md#custombuilder8)                  | 是   | 选择菜单的内容。                                             |
588| responseType | [TextResponseType](#textresponsetype11枚举说明)  | 是   | 选择菜单的响应类型。<br/>默认值:TextResponseType.LONG_PRESS |
589| options      | [SelectionMenuOptions](ts-basic-components-richeditor.md#selectionmenuoptions10) | 否   | 选择菜单的选项。                                             |
590
591### fontFeature<sup>12+</sup>
592
593fontFeature(value: string)
594
595设置文字特性效果,比如数字等宽的特性。
596
597格式为:normal \| \<feature-tag-value\>
598
599\<feature-tag-value\>的格式为:\<string\> \[ \<integer\> \| on \| off ]
600
601\<feature-tag-value\>的个数可以有多个,中间用','隔开。
602
603例如,使用等宽数字的输入格式为:"ss01" on。
604
605**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
606
607**系统能力:** SystemCapability.ArkUI.ArkUI.Full
608
609**参数:** 
610
611| 参数名 | 类型   | 必填 | 说明           |
612| ------ | ------ | ---- | -------------- |
613| value  | string | 是   | 文字特性效果。 |
614
615fontFeature属性列表<br/>
616![alt text](figures/arkts-fontfeature.png)
617
618设置 Font Feature 属性,Font Feature 是 OpenType 字体的高级排版能力,如支持连字、数字等宽等特性,一般用在自定义字体中,其能力需要字体本身支持。
619更多 Font Feature 能力介绍可参考 https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop 和 https://sparanoid.com/lab/opentype-features/
620
621>  **说明:**
622>
623>  不支持Text内同时存在文本内容和Span或ImageSpan子组件。如果同时存在,只显示Span或ImageSpan内的内容。
624>
625>  字体排版引擎会对开发者传入的宽度[width](ts-universal-attributes-size.md#width)进行向下取整,保证是整型像素后进行排版。如果字体排版引擎向上取整,可能会出现文字右侧被截断。
626>
627>  当多个Text组件在[Row](ts-container-row.md)容器内布局且没有设置具体的布局分配信息时,Text会以Row的最大尺寸进行布局。如果需要子组件主轴累加的尺寸不超过Row容器主轴的尺寸,可以设置[layoutWeight](ts-universal-attributes-size.md#layoutweight)或者是以[Flex](ts-universal-attributes-flex-layout.md)布局来约束子组件的主轴尺寸。
628
629### lineSpacing<sup>12+</sup>
630
631lineSpacing(value: LengthMetrics)
632
633设置文本的行间距,设置值不大于0时,取默认值0。
634
635**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
636
637**系统能力:** SystemCapability.ArkUI.ArkUI.Full
638
639**参数:** 
640
641| 参数名 | 类型                                                         | 必填 | 说明             |
642| ------ | ------------------------------------------------------------ | ---- | ---------------- |
643| value  | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 是   | 文本的行间距。默认值:0 |
644
645### privacySensitive<sup>12+</sup>
646
647privacySensitive(supported: boolean)
648
649设置是否支持卡片敏感隐私信息。
650
651**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
652
653**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
654
655**系统能力:** SystemCapability.ArkUI.ArkUI.Full
656
657**参数:**
658
659| 参数名    | 类型    | 必填 | 说明                                                         |
660| --------- | ------- | ---- | ------------------------------------------------------------ |
661| supported | boolean | 是   | 是否支持卡片敏感隐私信息。<br/>默认值为false,当设置为true时,隐私模式下文字将被遮罩为横杠“-”样式。<br/>**说明:** <br/>设置null则不敏感。<br/>进入隐私模式需要[卡片框架支持](./ts-universal-attributes-obscured.md)。 |
662
663### lineBreakStrategy<sup>12+</sup>
664
665lineBreakStrategy(strategy: LineBreakStrategy)
666
667设置折行规则。该属性在wordBreak不等于breakAll的时候生效,不支持连词符。
668
669**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
670
671**系统能力:** SystemCapability.ArkUI.ArkUI.Full
672
673**参数:** 
674
675| 参数名   | 类型                                                         | 必填 | 说明                                                    |
676| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------- |
677| strategy | [LineBreakStrategy](ts-appendix-enums.md#linebreakstrategy12) | 是   | 文本的折行规则。 <br />默认值:LineBreakStrategy.GREEDY |
678
679### textSelectable<sup>12+</sup>
680
681textSelectable(mode: TextSelectableMode)
682
683设置是否支持文本可选择、可获焦以及Touch后能否获取焦点。
684
685**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
686
687**系统能力:** SystemCapability.ArkUI.ArkUI.Full
688
689**参数:** 
690
691| 参数名 | 类型                                          | 必填 | 说明                                          |
692| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
693| mode  | [TextSelectableMode](ts-appendix-enums.md#textselectablemode12) | 是   | 文本是否支持可选择、可获焦。 <br />默认值:TextSelectableMode.SELECTABLE_UNFOCUSABLE |
694
695### editMenuOptions<sup>12+</sup>
696
697editMenuOptions(editMenu: EditMenuOptions)
698
699设置自定义菜单扩展项,允许用户设置扩展项的文本内容、图标、回调方法。
700
701**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
702
703**系统能力:** SystemCapability.ArkUI.ArkUI.Full
704
705**参数:** 
706
707| 参数名 | 类型                                          | 必填 | 说明                                          |
708| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
709| editMenu  | [EditMenuOptions](ts-text-common.md#editmenuoptions对象说明) | 是   | 扩展菜单选项。 |
710
711### minFontScale<sup>12+</sup>
712
713minFontScale(scale: number | Resource)
714
715设置文本最小的字体缩放倍数。
716
717**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
718
719**系统能力:** SystemCapability.ArkUI.ArkUI.Full
720
721**参数:** 
722
723| 参数名 | 类型                                          | 必填 | 说明                                          |
724| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
725| scale  | number \| [Resource](ts-types.md#resource) | 是   | 文本最小的字体缩放倍数。<br/>取值范围:(0, 1]<br/>**说明:** <br/>设置的值小于0时,按值为0处理,设置的值大于1,按值为1处理,异常值默认不生效。 |
726
727### maxFontScale<sup>12+</sup>
728
729maxFontScale(scale: number | Resource)
730
731设置文本最大的字体缩放倍数。
732
733**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
734
735**系统能力:** SystemCapability.ArkUI.ArkUI.Full
736
737**参数:** 
738
739| 参数名 | 类型                                          | 必填 | 说明                                          |
740| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
741| scale  | number \| [Resource](ts-types.md#resource) | 是   | 文本最大的字体缩放倍数。<br/>取值范围:[1, +∞)<br/>**说明:** <br/>设置的值小于1时,按值为1处理,异常值默认不生效。 |
742
743### halfLeading<sup>12+</sup>
744
745halfLeading(halfLeading: boolean)
746
747设置文本是否将行间距平分至行的顶部与底部。
748
749组件侧设置halfLeading优先级高于module.json5配置文件中的halfLeading配置项。
750
751**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
752
753**系统能力:** SystemCapability.ArkUI.ArkUI.Full
754
755**参数:** 
756
757| 参数名 | 类型                                          | 必填 | 说明                                          |
758| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
759| halfLeading | boolean | 是  | 文本是否将行间距平分至行的顶部与底部。<br/>true表示将行间距平分至行的顶部与底部,false则不平分。<br/>默认值:false |
760
761### font<sup>12+</sup>
762
763font(fontValue: Font, options?: FontSettingOptions)
764
765设置文本样式,支持设置字体配置项。
766
767仅Text组件生效,其子组件不生效。
768
769**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
770
771**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
772
773**系统能力:** SystemCapability.ArkUI.ArkUI.Full
774
775**参数:** 
776
777| 参数名 | 类型                                          | 必填 | 说明                                          |
778| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
779| fontValue | [Font](ts-types.md#font) | 是  | 设置文本样式。 |
780| options | [FontSettingOptions](ts-text-common.md#fontsettingoptions12对象说明) | 否  | 设置字体配置项。 |
781
782### fontWeight<sup>12+</sup>
783
784fontWeight(weight: number | FontWeight | string, options?: FontSettingOptions)
785
786设置文本字重,支持设置字体配置项。
787
788仅Text组件生效,其子组件不生效。
789
790**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
791
792**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
793
794**系统能力:** SystemCapability.ArkUI.ArkUI.Full
795
796**参数:** 
797
798| 参数名 | 类型                                          | 必填 | 说明                                          |
799| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
800| weight | number&nbsp;\|&nbsp;[FontWeight](ts-appendix-enums.md#fontweight)&nbsp;\|&nbsp;string | 是  | 设置文本字重。 |
801| options | [FontSettingOptions](ts-text-common.md#fontsettingoptions12对象说明) | 否  | 设置字体配置项。 |
802
803### enableHapticFeedback<sup>13+</sup>
804
805enableHapticFeedback(isEnabled: boolean)
806
807设置是否开启触控反馈。
808
809**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
810
811**系统能力:** SystemCapability.ArkUI.ArkUI.Full
812
813**参数:** 
814
815| 参数名 | 类型    | 必填 | 说明                               |
816| ------ | ------- | ---- | ---------------------------------- |
817| isEnabled | boolean | 是   | 是否开启触控反馈。<br/>默认值:true |
818
819>  **说明:**
820>
821>  开启触控反馈时,需要在工程的module.json5中配置requestPermissions字段开启振动权限,配置如下:
822> ```json
823> "requestPermissions": [
824>  {
825>     "name": "ohos.permission.VIBRATE",
826>  }
827> ]
828> ```
829
830### caretColor<sup>14+</sup>
831
832caretColor(value: ResourceColor)
833
834设置文本框选中区域手柄颜色。
835
836**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
837
838**系统能力:** SystemCapability.ArkUI.ArkUI.Full
839
840**参数:**
841
842| 参数名 | 类型                                       | 必填 | 说明                                   |
843| ------ | ------------------------------------------ | ---- | -------------------------------------- |
844| value  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 文本选中手柄颜色。<br/>默认值:'#007DFF' |
845
846### selectedBackgroundColor<sup>14+</sup>
847
848selectedBackgroundColor(value: ResourceColor)
849
850设置文本选中底板颜色。如果未设置不透明度,默认为20%不透明度。
851
852**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
853
854**系统能力:** SystemCapability.ArkUI.ArkUI.Full
855
856**参数:**
857
858| 参数名 | 类型                                       | 必填 | 说明                                       |
859| ------ | ------------------------------------------ | ---- | ------------------------------------------ |
860| value  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 文本选中底板颜色。<br/>默认为20%不透明度。<br/>默认值:'#007DFF' |
861
862## TextSpanType<sup>11+</sup>枚举说明
863
864[Span](ts-basic-components-span.md)类型信息。
865
866**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
867
868**系统能力:** SystemCapability.ArkUI.ArkUI.Full
869
870| 名称 | 说明 |
871| -------- | -------- |
872| TEXT | Span为文字类型。 |
873| IMAGE | Span为图像类型。|
874| MIXED | Span为图文混合类型。|
875
876## TextResponseType<sup>11+</sup>枚举说明
877
878**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
879
880**系统能力:** SystemCapability.ArkUI.ArkUI.Full
881
882| 名称         | 说明          |
883| ---------- | ------------- |
884| RIGHT_CLICK | 通过鼠标右键触发菜单弹出。 |
885| LONG_PRESS  | 通过长按触发菜单弹出。   |
886| SELECT | 通过鼠标选中触发菜单弹出。 |
887
888## 事件
889
890除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件:
891
892### onCopy<sup>11+</sup>
893
894onCopy(callback:(value:&nbsp;string)&nbsp;=&gt;&nbsp;void)
895
896长按文本内部区域弹出剪贴板后,点击剪切板复制按钮,触发该回调。目前文本复制仅支持文本。
897
898**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
899
900**系统能力:** SystemCapability.ArkUI.ArkUI.Full
901
902**参数:** 
903
904| 参数名 | 类型   | 必填 | 说明             |
905| ------ | ------ | ---- | ---------------- |
906| value  | string | 是   | 复制的文本内容。 |
907
908### onTextSelectionChange<sup>11+</sup>
909
910onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)
911
912文本选择的位置发生变化时,触发该回调。
913
914**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
915
916**系统能力:** SystemCapability.ArkUI.ArkUI.Full
917
918**参数:** 
919
920| 参数名         | 类型   | 必填 | 说明                 |
921| -------------- | ------ | ---- | -------------------- |
922| selectionStart | number | 是   | 所选文本的起始位置。 |
923| selectionEnd   | number | 是   | 所选文本的结束位置。 |
924
925## TextOptions<sup>11+</sup>
926
927Text初始化参数。
928
929**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
930
931**系统能力:** SystemCapability.ArkUI.ArkUI.Full
932
933| 名称 | 类型 | 必填 | 说明 |
934| -------- | -------- | -------- | -------- |
935| controller | [TextController](#textcontroller11)  | 是 | 文本控制器。 |
936
937## TextController<sup>11+</sup>
938
939Text组件的控制器。
940
941**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
942
943**系统能力:** SystemCapability.ArkUI.ArkUI.Full
944
945### 导入对象
946
947```
948controller: TextController = new TextController()
949```
950
951### closeSelectionMenu
952
953closeSelectionMenu(): void
954
955关闭自定义选择菜单或系统默认选择菜单。
956
957**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
958
959**系统能力:** SystemCapability.ArkUI.ArkUI.Full
960
961### setStyledString<sup>12+</sup>
962
963setStyledString(value: StyledString): void
964
965触发绑定或更新属性字符串。
966
967**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
968
969**系统能力:** SystemCapability.ArkUI.ArkUI.Full
970
971**参数:**
972
973| 参数名   | 类型   | 必填   | 说明                |
974| ----- | ------ | ---- | ------------------- |
975| value | [StyledString](ts-universal-styled-string.md#styledstring) | 是    | 属性字符串。<br/>**说明:** <br/>StyledString的子类[MutableStyledString](ts-universal-styled-string.md#mutablestyledstring)也可以作为入参值。 |
976
977### getLayoutManager<sup>12+</sup>
978
979getLayoutManager(): LayoutManager
980
981获取布局管理器对象。
982
983**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
984
985**系统能力:** SystemCapability.ArkUI.ArkUI.Full
986
987**返回值:**
988
989| 类型                                       | 说明      |
990| ---------------------------------------- | ------- |
991| [LayoutManager](ts-text-common.md#LayoutManager) | 布局管理器对象。 |
992
993## 示例
994
995### 示例1
996
997textAlign、maxLines、textOverflow、lineHeight属性接口使用示例
998
999```ts
1000// xxx.ets
1001@Extend(Text)
1002function style(TextAlign: TextAlign) {
1003  .textAlign(TextAlign)
1004  .fontSize(12)
1005  .border({ width: 1 })
1006  .padding(10)
1007  .width('100%')
1008}
1009
1010@Entry
1011@Component
1012struct TextExample1 {
1013  build() {
1014    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
1015      // 文本水平方向对齐方式设置
1016      // 单行文本
1017      Text('textAlign').fontSize(9).fontColor(0xCCCCCC)
1018      Text('TextAlign set to Center.')
1019        .style(TextAlign.Center)
1020      Text('TextAlign set to Start.')
1021        .style(TextAlign.Start)
1022      Text('TextAlign set to End.')
1023        .style(TextAlign.End)
1024
1025      // 多行文本
1026      Text('This is the text content with textAlign set to Center.')
1027        .style(TextAlign.Center)
1028      Text('This is the text content with textAlign set to Start.')
1029        .style(TextAlign.Start)
1030      Text('This is the text content with textAlign set to End.')
1031        .style(TextAlign.End)
1032
1033
1034      // 文本超长时显示方式
1035      Text('TextOverflow+maxLines').fontSize(9).fontColor(0xCCCCCC)
1036      // 超出maxLines截断内容展示
1037      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.')
1038        .textOverflow({ overflow: TextOverflow.Clip })
1039        .maxLines(1)
1040        .style(TextAlign.Start)
1041
1042      // 超出maxLines展示省略号
1043      Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.')
1044        .textOverflow({ overflow: TextOverflow.Ellipsis })
1045        .maxLines(1)
1046        .style(TextAlign.Start)
1047
1048      Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
1049      Text('This is the text with the line height set. This is the text with the line height set.')
1050        .style(TextAlign.Start)
1051      Text('This is the text with the line height set. This is the text with the line height set.')
1052        .style(TextAlign.Start)
1053        .lineHeight(20)
1054    }.height(600).width(340).padding({ left: 35, right: 35, top: 35 })
1055  }
1056}
1057```
1058![textExp1](figures/textExp1.png)
1059
1060### 示例2
1061
1062decoration、baselineOffset、letterSpacing、textCase属性接口使用示例
1063
1064```ts
1065@Extend(Text)
1066function style() {
1067  .fontSize(12)
1068  .border({ width: 1 })
1069  .padding(10)
1070  .width('100%')
1071}
1072
1073@Entry
1074@Component
1075struct TextExample2 {
1076  build() {
1077    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
1078      Text('decoration').fontSize(9).fontColor(0xCCCCCC)
1079      Text('This is the text content with the decoration set to LineThrough and the color set to Red.')
1080        .decoration({
1081          type: TextDecorationType.LineThrough,
1082          color: Color.Red
1083        })
1084        .style()
1085
1086      Text('This is the text content with the decoration set to Overline and the color set to Red.')
1087        .decoration({
1088          type: TextDecorationType.Overline,
1089          color: Color.Red,
1090          style: TextDecorationStyle.DOTTED
1091        })
1092        .style()
1093
1094      Text('This is the text content with the decoration set to Underline and the color set to Red.')
1095        .decoration({
1096          type: TextDecorationType.Underline,
1097          color: Color.Red,
1098          style: TextDecorationStyle.WAVY
1099        })
1100        .style()
1101
1102      // 文本基线偏移
1103      Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC)
1104      Text('This is the text content with baselineOffset 0.')
1105        .baselineOffset(0)
1106        .style()
1107      Text('This is the text content with baselineOffset 30.')
1108        .baselineOffset(30)
1109        .style()
1110      Text('This is the text content with baselineOffset -20.')
1111        .baselineOffset(-20)
1112        .style()
1113
1114      // 文本字符间距
1115      Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
1116      Text('This is the text content with letterSpacing 0.')
1117        .letterSpacing(0)
1118        .style()
1119      Text('This is the text content with letterSpacing 3.')
1120        .letterSpacing(3)
1121        .style()
1122      Text('This is the text content with letterSpacing -1.')
1123        .letterSpacing(-1)
1124        .style()
1125
1126      Text('textCase').fontSize(9).fontColor(0xCCCCCC)
1127      Text('This is the text content with textCase set to Normal.')
1128        .textCase(TextCase.Normal)
1129        .style()
1130      // 文本全小写展示
1131      Text('This is the text content with textCase set to LowerCase.')
1132        .textCase(TextCase.LowerCase)
1133        .style()
1134      // 文本全大写展示
1135      Text('This is the text content with textCase set to UpperCase.')
1136        .textCase(TextCase.UpperCase)
1137        .style()
1138
1139    }.height(700).width(350).padding({ left: 35, right: 35, top: 35 })
1140  }
1141}
1142```
1143![textExp1](figures/textExp2.png)
1144
1145### 示例3
1146
1147textShadow、heightAdaptivePolicy、TextOverflow.MARQUEE使用示例
1148
1149```ts
1150@Extend(Text)
1151function style(HeightAdaptivePolicy: TextHeightAdaptivePolicy) {
1152  .width('80%')
1153  .height(90)
1154  .borderWidth(1)
1155  .minFontSize(10)
1156  .maxFontSize(30)
1157  .maxLines(2)
1158  .textOverflow({ overflow: TextOverflow.Ellipsis })
1159  .heightAdaptivePolicy(HeightAdaptivePolicy)
1160}
1161
1162@Entry
1163@Component
1164struct TextExample3 {
1165  build() {
1166    Column() {
1167      Text('textShadow').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
1168      // 设置文字阴影效果
1169      Text('textShadow')
1170        .width('80%')
1171        .height(55)
1172        .fontSize(40)
1173        .lineHeight(55)
1174        .textAlign(TextAlign.Center)
1175        .textShadow({
1176          radius: 10,
1177          color: Color.Black,
1178          offsetX: 0,
1179          offsetY: 0
1180        })
1181        .borderWidth(1)
1182      Divider()
1183      // 设置文本自适应高度的方式
1184      Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
1185      Text('This is the text with the height adaptive policy set')
1186        .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
1187      Text('This is the text with the height adaptive policy set')
1188        .style(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
1189      Text('This is the text with the height adaptive policy set')
1190        .style(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)
1191      Divider()
1192      Text('marquee').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
1193      // 设置文本超长时以跑马灯的方式展示
1194      Text('This is the text with the text overflow set marquee')
1195        .width(300)
1196        .borderWidth(1)
1197        .textOverflow({ overflow: TextOverflow.MARQUEE })
1198    }
1199  }
1200}
1201```
1202
1203![](figures/text_3.gif)
1204
1205### 示例4
1206ellipsisMode和wordBreak使用示例
1207
1208```ts
1209// xxx.ets
1210@Entry
1211@Component
1212struct TextExample4 {
1213  @State text: string =
1214    'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.'
1215  @State ellipsisModeIndex: number = 0;
1216  @State ellipsisMode: EllipsisMode[] = [EllipsisMode.START, EllipsisMode.CENTER, EllipsisMode.END]
1217  @State ellipsisModeStr: string[] = ['START', 'CENTER', 'END']
1218  @State wordBreakIndex: number = 0;
1219  @State wordBreak: WordBreak[] = [WordBreak.NORMAL, WordBreak.BREAK_ALL, WordBreak.BREAK_WORD]
1220  @State wordBreakStr: string[] = ['NORMAL', 'BREAK_ALL', 'BREAK_WORD']
1221  @State textClip: boolean = false
1222
1223  build() {
1224    Column({ space: 10 }) {
1225      Text(this.text)
1226        .fontSize(16)
1227        .border({ width: 1 })
1228        .lineHeight(20)
1229        .maxLines(1)
1230        .textOverflow({ overflow: TextOverflow.Ellipsis })
1231        .ellipsisMode(this.ellipsisMode[this.ellipsisModeIndex])
1232        .width(300)
1233        .margin({ left: 20, top: 20 })
1234
1235      Row() {
1236        Button('更改省略号位置:' + this.ellipsisModeStr[this.ellipsisModeIndex]).onClick(() => {
1237          this.ellipsisModeIndex++
1238          if (this.ellipsisModeIndex > (this.ellipsisModeStr.length - 1)) {
1239            this.ellipsisModeIndex = 0
1240          }
1241        })
1242      }
1243
1244      Text('This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.')
1245        .fontSize(12)
1246        .border({ width: 1 })
1247        .wordBreak(WordBreak.NORMAL)
1248        .lineHeight(20)
1249        .maxLines(2)
1250        .clip(this.textClip)
1251        .width(260)
1252      Row() {
1253        Button('切换clip:' + this.textClip).onClick(() => {
1254          this.textClip = !this.textClip
1255        })
1256      }
1257
1258      Text(this.text)
1259        .fontSize(12)
1260        .border({ width: 1 })
1261        .maxLines(2)
1262        .textOverflow({ overflow: TextOverflow.Ellipsis })
1263        .wordBreak(this.wordBreak[this.wordBreakIndex])
1264        .lineHeight(20)
1265        .width(260)
1266      Row() {
1267        Button('更改wordBreak模式:' + this.wordBreakStr[this.wordBreakIndex]).onClick(() => {
1268          this.wordBreakIndex++
1269          if (this.wordBreakIndex > (this.wordBreakStr.length - 1)) {
1270            this.wordBreakIndex = 0
1271          }
1272        })
1273      }
1274    }
1275  }
1276}
1277```
1278
1279![](figures/textExample4.gif)
1280
1281### 示例5
1282selection和onCopy使用示例
1283
1284```ts
1285@Entry
1286@Component
1287struct TextExample5 {
1288  @State onCopy: string = ''
1289  @State text: string = 'This is set selection to Selection text content This is set selection to Selection text content.'
1290  @State start: number = 0
1291  @State end: number = 20
1292
1293  build() {
1294    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
1295      Text(this.text)
1296        .fontSize(12)
1297        .border({ width: 1 })
1298        .lineHeight(20)
1299        .margin(30)
1300        .copyOption(CopyOptions.InApp)
1301        .selection(this.start, this.end)
1302        .onCopy((value: string) => {
1303          this.onCopy = value
1304        })
1305      Button('Set text selection')
1306        .margin({left:20})
1307        .onClick(() => {
1308          // 变更文本选中起始点、终点
1309          this.start = 10
1310          this.end = 30
1311        })
1312      Text(this.onCopy).fontSize(12).margin(10).key('copy')
1313    }.height(600).width(335).padding({ left: 35, right: 35, top: 35 })
1314  }
1315}
1316```
1317![](figures/textExample5.png)
1318
1319### 示例6
1320enableDataDetector和dataDetectorConfig使用示例
1321
1322```ts
1323@Entry
1324@Component
1325struct TextExample6 {
1326  @State phoneNumber: string = '(86) (755) ********';
1327  @State url: string = 'www.********.com';
1328  @State email: string = '***@example.com';
1329  @State address: string = 'XX省XX市XX区XXXX';
1330  @State datetime: string = 'XX年XX月XX日XXXX';
1331  @State enableDataDetector: boolean = true;
1332  @State types: TextDataDetectorType[] = [];
1333
1334  build() {
1335    Row() {
1336      Column() {
1337        Text(
1338          '电话号码:' + this.phoneNumber + '\n' +
1339          '链接:' + this.url + '\n' +
1340          '邮箱:' + this.email + '\n' +
1341          '地址:' + this.address + '\n' +
1342          '时间:' + this.datetime
1343        )
1344          .fontSize(16)
1345          .copyOption(CopyOptions.InApp)
1346          .enableDataDetector(this.enableDataDetector)
1347          .dataDetectorConfig({types : this.types, onDetectResultUpdate: (result: string)=>{}})
1348          .textAlign(TextAlign.Center)
1349          .borderWidth(1)
1350          .padding(10)
1351          .width('100%')
1352      }
1353      .width('100%')
1354    }
1355    .height('100%')
1356  }
1357}
1358```
1359
1360![](figures/text7.png)
1361
1362### 示例7
1363
1364bindSelectionMenu,onTextSelectionChange及closeSelectionMenu使用示例
1365
1366```ts
1367@Entry
1368@Component
1369struct TextExample7 {
1370  controller: TextController = new TextController();
1371  options: TextOptions = { controller: this.controller };
1372
1373  build() {
1374    Column() {
1375      Column() {
1376        Text(undefined, this.options) {
1377          Span('Hello World')
1378          ImageSpan($r('app.media.icon'))
1379            .width('100px')
1380            .height('100px')
1381            .objectFit(ImageFit.Fill)
1382            .verticalAlign(ImageSpanAlignment.CENTER)
1383        }
1384        .copyOption(CopyOptions.InApp)
1385        .bindSelectionMenu(TextSpanType.IMAGE, this.LongPressImageCustomMenu, TextResponseType.LONG_PRESS, {
1386          onDisappear: () => {
1387            console.info(`自定义选择菜单关闭时回调`);
1388          },
1389          onAppear: () => {
1390            console.info(`自定义选择菜单弹出时回调`);
1391          }
1392        })
1393        .bindSelectionMenu(TextSpanType.TEXT, this.RightClickTextCustomMenu, TextResponseType.RIGHT_CLICK)
1394        .bindSelectionMenu(TextSpanType.MIXED, this.SelectMixCustomMenu, TextResponseType.SELECT)
1395        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
1396          console.info(`文本选中区域变化回调, selectionStart: ${selectionStart}, selectionEnd: ${selectionEnd}`);
1397        })
1398        .borderWidth(1)
1399        .borderColor(Color.Red)
1400        .width(200)
1401        .height(100)
1402      }
1403      .width('100%')
1404      .backgroundColor(Color.White)
1405      .alignItems(HorizontalAlign.Start)
1406      .padding(25)
1407    }
1408    .height('100%')
1409  }
1410
1411  @Builder
1412  RightClickTextCustomMenu() {
1413    Column() {
1414      Menu() {
1415        MenuItemGroup() {
1416          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 1", labelInfo: "" })
1417            .onClick((event) => {
1418              this.controller.closeSelectionMenu();
1419            })
1420          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 2", labelInfo: "" })
1421          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 3", labelInfo: "" })
1422        }
1423      }
1424      .MenuStyles()
1425    }
1426  }
1427
1428  @Builder
1429  LongPressImageCustomMenu() {
1430    Column() {
1431      Menu() {
1432        MenuItemGroup() {
1433          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 1", labelInfo: "" })
1434            .onClick((event) => {
1435              this.controller.closeSelectionMenu();
1436            })
1437          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 2", labelInfo: "" })
1438          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 3", labelInfo: "" })
1439        }
1440      }
1441      .MenuStyles()
1442    }
1443  }
1444
1445  @Builder
1446  SelectMixCustomMenu() {
1447    Column() {
1448      Menu() {
1449        MenuItemGroup() {
1450          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 1", labelInfo: "" })
1451            .onClick((event) => {
1452              this.controller.closeSelectionMenu();
1453            })
1454          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 2", labelInfo: "" })
1455          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 3", labelInfo: "" })
1456        }
1457      }
1458      .MenuStyles()
1459    }
1460  }
1461}
1462
1463@Extend(Menu)
1464function MenuStyles() {
1465  .radius($r('sys.float.ohos_id_corner_radius_card'))
1466  .clip(true)
1467  .backgroundColor('#F0F0F0')
1468}
1469```
1470
1471![](figures/textBindSelectionMenu.gif)
1472
1473### 示例8
1474fontFeature、lineSpacing和lineBreakStrategy使用示例。
1475
1476```ts
1477import { LengthMetrics } from '@kit.ArkUI'
1478
1479@Extend(Text) function lineSpacingValue(LineSpacing: LengthMetrics|undefined) {
1480  .lineSpacing(LineSpacing)
1481  .fontSize(12)
1482  .border({ width: 1 })
1483}
1484@Entry
1485@Component
1486struct TextExample8 {
1487  @State message1: string = "They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" +
1488    "The built-in components include buttons radio buttonsprogress indicators and text You can set the rendering effectof thesecomponents in method chaining mode," +
1489    "page components are divided into independent UI units to implementindependent creation development and reuse of different units on pages making pages more engineering-oriented.";
1490  @State lineBreakStrategyIndex: number = 0;
1491  @State lineBreakStrategy: LineBreakStrategy[] = [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED]
1492  @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED']
1493  build() {
1494    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
1495      Text('lineSpacing').fontSize(9).fontColor(0xCCCCCC)
1496      Text('This is a context with no lineSpacing set.')
1497        .lineSpacingValue(undefined)
1498      Text( 'This is a context with lineSpacing set to 20_px.')
1499        .lineSpacingValue(LengthMetrics.px(20))
1500      Text('This is the context with lineSpacing set to 20_vp.')
1501        .lineSpacingValue(LengthMetrics.vp(20))
1502      Text('This is the context with lineSpacing set to 20_fp.')
1503        .lineSpacingValue(LengthMetrics.fp(20))
1504      Text('This is the context with lineSpacing set to 20_lpx.')
1505        .lineSpacingValue(LengthMetrics.lpx(20))
1506      Text('This is the context with lineSpacing set to 100%.')
1507        .lineSpacingValue(LengthMetrics.percent(1))
1508      Text('fontFeature').fontSize(9).fontColor(0xCCCCCC)
1509      Text('This is ss01 on : 0123456789')
1510        .fontSize(20)
1511        .fontFeature("\"ss01\" on")
1512      Text('This is ss01 off: 0123456789')
1513        .fontSize(20)
1514        .fontFeature("\"ss01\" off")
1515      Text('lineBreakStrategy').fontSize(9).fontColor(0xCCCCCC)
1516      Text(this.message1)
1517        .fontSize(12)
1518        .border({ width: 1 })
1519        .padding(10)
1520        .width('100%')
1521        .lineBreakStrategy(this.lineBreakStrategy[this.lineBreakStrategyIndex])
1522      Row() {
1523        Button('当前lineBreakStrategy模式:' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => {
1524          this.lineBreakStrategyIndex++
1525          if(this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) {
1526            this.lineBreakStrategyIndex = 0
1527          }
1528        })
1529      }
1530    }.height(600).width(350).padding({ left: 35, right: 35, top: 35 })
1531  }
1532}
1533```
1534
1535![](figures/TextExample8.gif)
1536
1537### 示例9
1538getLayoutManager使用示例。
1539
1540```ts
1541@Entry
1542@Component
1543struct TextExample9 {
1544  @State lineCount: string = ""
1545  @State glyphPositionAtCoordinate: string = ""
1546  @State lineMetrics: string = ""
1547  controller: TextController = new TextController()
1548  @State textStr: string =
1549    'Hello World! 您好,世界!'
1550
1551  build() {
1552    Scroll() {
1553      Column() {
1554        Text('Text组件getLayoutManager接口获取段落相对组件的信息')
1555          .fontSize(9)
1556          .fontColor(0xCCCCCC)
1557          .width('90%')
1558          .padding(10)
1559        Text(this.textStr, { controller: this.controller })
1560          .fontSize(25)
1561          .borderWidth(1)
1562          .onAreaChange(() => {
1563            let layoutManager: LayoutManager = this.controller.getLayoutManager()
1564            this.lineCount = "LineCount: " + layoutManager.getLineCount()
1565          })
1566
1567        Text('LineCount').fontSize(9).fontColor(0xCCCCCC).width('90%').padding(10)
1568        Text(this.lineCount)
1569
1570        Text('GlyphPositionAtCoordinate').fontSize(9).fontColor(0xCCCCCC).width('90%').padding(10)
1571        Button("相对组件坐标[150,50]字形信息")
1572          .onClick(() => {
1573            let layoutManager: LayoutManager = this.controller.getLayoutManager()
1574            let position: PositionWithAffinity = layoutManager.getGlyphPositionAtCoordinate(150, 50)
1575            this.glyphPositionAtCoordinate =
1576              "相对组件坐标[150,50] glyphPositionAtCoordinate position: " + position.position + " affinity: " +
1577              position.affinity
1578          })
1579          .margin({ bottom: 20, top: 10 })
1580        Text(this.glyphPositionAtCoordinate)
1581
1582        Text('LineMetrics').fontSize(9).fontColor(0xCCCCCC).width('90%').padding(10)
1583        Button("首行行信息、文本样式信息、以及字体属性信息")
1584          .onClick(() => {
1585            let layoutManager: LayoutManager = this.controller.getLayoutManager()
1586            let lineMetrics: LineMetrics = layoutManager.getLineMetrics(0)
1587            this.lineMetrics = "lineMetrics is " + JSON.stringify(lineMetrics) + '\n\n'
1588            let runMetrics = lineMetrics.runMetrics
1589            runMetrics.forEach((value, key) => {
1590              this.lineMetrics += "runMetrics key is " + key + " " + JSON.stringify(value) + "\n\n"
1591            });
1592          })
1593          .margin({ bottom: 20, top: 10 })
1594        Text(this.lineMetrics)
1595      }
1596      .margin({ top: 100, left: 8, right: 8 })
1597    }
1598  }
1599}
1600```
1601
1602![textLayoutManager](figures/textLayoutManager.gif)
1603
1604### 示例10
1605textSelectable使用示例,展示了设置TextSelectMode.SELECTABLE_FOCUSABLE属性时能够触发键盘框选文本功能。
1606
1607```ts
1608@Entry
1609@Component
1610struct TextExample10 {
1611  @State message: string = 'TextTextTextTextTextTextTextText' + 'TextTextTextTextTextTextTextTextTextTextTextTextTextTextTextText';
1612  
1613  build() {
1614    Column() {
1615      Text(this.message)
1616        .width(300)
1617        .height(100)
1618        .maxLines(5)
1619        .fontColor(Color.Black)
1620        .copyOption(CopyOptions.InApp)
1621        .selection(3, 8)
1622        .textSelectable(TextSelectableMode.SELECTABLE_FOCUSABLE)
1623    }.width('100%').margin({ top: 100 })
1624  }
1625}
1626```
1627
1628![textTextSelectableMode](figures/textTextSelectableMode.gif)
1629
1630### 示例11
1631
1632editMenuOptions使用示例,展示设置自定义菜单扩展项的文本内容、图标、回调方法。
1633
1634```ts
1635// xxx.ets
1636@Entry
1637@Component
1638struct TextExample11 {
1639  @State text: string = 'Text editMenuOptions'
1640
1641  onCreateMenu(menuItems: Array<TextMenuItem>) {
1642    menuItems.forEach((value, index) => {
1643      value.icon = $r('app.media.startIcon')
1644      if (value.id.equals(TextMenuItemId.COPY)) {
1645        value.content = "复制change"
1646      }
1647      if (value.id.equals(TextMenuItemId.SELECT_ALL)) {
1648        value.content = "全选change"
1649      }
1650    })
1651    let item1: TextMenuItem = {
1652      content: 'custom1',
1653      icon: $r('app.media.startIcon'),
1654      id: TextMenuItemId.of('custom1'),
1655    }
1656    let item2: TextMenuItem = {
1657      content: 'custom2',
1658      id: TextMenuItemId.of('custom2'),
1659      icon: $r('app.media.startIcon'),
1660    }
1661    menuItems.push(item1)
1662    menuItems.unshift(item2)
1663    return menuItems
1664  }
1665
1666  build() {
1667    Column() {
1668      Text(this.text)
1669        .fontSize(20)
1670        .copyOption(CopyOptions.LocalDevice)
1671        .editMenuOptions({
1672          onCreateMenu: this.onCreateMenu, onMenuItemClick: (menuItem: TextMenuItem, textRange: TextRange) => {
1673            if (menuItem.id.equals(TextMenuItemId.of("custom2"))) {
1674              console.log("拦截 id: custom2 start:" + textRange.start + "; end:" + textRange.end)
1675              return true;
1676            }
1677            if (menuItem.id.equals(TextMenuItemId.COPY)) {
1678              console.log("拦截 COPY start:" + textRange.start + "; end:" + textRange.end)
1679              return true;
1680            }
1681            if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
1682              console.log("不拦截 SELECT_ALL start:" + textRange.start + "; end:" + textRange.end)
1683              return false;
1684            }
1685            return false;
1686          }
1687        })
1688        .margin({ top: 100 })
1689    }
1690    .width("90%")
1691    .margin("5%")
1692  }
1693}
1694```
1695
1696![textEditMenuOptions](figures/textEditMenuOptions.gif)
1697
1698### 示例12
1699
1700halfLeading使用示例。
1701
1702```ts
1703// xxx.ets
1704@Entry
1705@Component
1706struct TextExample12 {
1707  build() {
1708    Column({ space: 10 }) {
1709      // 设置文本是否居中对齐
1710      Text('halfLeading').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
1711      Text("This is the text with the halfLeading set.")
1712        .lineHeight(60)
1713        .halfLeading(true)
1714        .borderWidth(1)
1715        .width('80%')
1716      Text("This is the text without the halfLeading set.")
1717        .lineHeight(60)
1718        .halfLeading(false)
1719        .borderWidth(1)
1720        .width('80%')
1721    }
1722  }
1723}
1724```
1725
1726![textHalfLeading](figures/textHalfLeading.PNG)
1727
1728### 示例13
1729
1730该示例展示了如何配置隐私隐藏,效果展示需要卡片框架支持
1731
1732```ts
1733@Entry
1734@Component
1735struct ImageExample {
1736  build() {
1737    Column({ space: 10 }) {
1738      Text("privacySensitive")
1739        .privacySensitive(true)
1740        .margin({top :30})
1741    }
1742    .alignItems(HorizontalAlign.Center)
1743    .width("100%")
1744  }
1745}
1746```
1747
1748![textPrivacySensitive](figures/textPrivacySensitive.gif)