文本组件
Text
是显示文本的基础组件之一,它可以包含子组件 Span
,当包含 Span
时不生效,只显示 Span
的内容。
Text 定义介绍
bash
interface TextInterface {
(content?: string | Resource): TextAttribute;
}
- content:要显示的文本内容,一个简单的例子如下:
bash
Text("Hello, OpenHarmony")
Text('Hello, OpenHarmony')
.width('100%')
.textAlign(TextAlign.Center)
Text('Hello, OpenHarmony, Hello, OpenHarmony, Hello, OpenHarmony, Hello, OpenHarmony')
.maxLines(1)
.textOverflow({overflow: TextOverflow.Ellipsis})
样例运行结果如下图所示:
Text 属性介绍
bash
declare class TextAttribute extends CommonMethod<TextAttribute> {
fontColor(value: ResourceColor): TextAttribute;
fontSize(value: number | string | Resource): TextAttribute;
minFontSize(value: number | string | Resource): TextAttribute;
maxFontSize(value: number | string | Resource): TextAttribute;
fontStyle(value: FontStyle): TextAttribute;
fontWeight(value: number | FontWeight | string): TextAttribute;
textAlign(value: TextAlign): TextAttribute;
lineHeight(value: number | string | Resource): TextAttribute;
textOverflow(value: { overflow: TextOverflow }): TextAttribute;
fontFamily(value: string | Resource): TextAttribute;
maxLines(value: number): TextAttribute;
decoration(value: { type: TextDecorationType; color?: ResourceColor }): TextAttribute;
letterSpacing(value: number | string): TextAttribute;
textCase(value: TextCase): TextAttribute;
baselineOffset(value: number | string): TextAttribute;
}
textAlign
设置文本的对其方式,对齐参考系是 Text
组件本身,只有 Text
组件本身的宽度大于文本内容长度, textAlign
属性才起作用, TextAlign
定义了以下 3 种类型:
Start(默认值)
:根据文字书写相同的方向对齐,比如中文从左往右排版,那么文本则靠左对齐。Center
:文本居中对齐。End
:根据文字书写相反的方向对齐,比如中文从左往右排版,那么文本则靠右对齐。
简单样例如下所示:
bash
Text("Hello, OpenHarmony")
.backgroundColor('#aabbcc')
.textAlign(TextAlign.Center) // 宽度等于文本内容长度,textAlign不起作用
Text('Hello, OpenHarmony')
.backgroundColor('#ccaabb')
.margin({top: 2})
.width(200) // 宽度大于文本内容长度,textAlign起作用
.textAlign(TextAlign.End)
Text('Hello, OpenHarmony')
.backgroundColor('#bbccaa')
.margin({top: 2})
.width('100%') // 宽度大于文本内容长度,textAlign起作用
.textAlign(TextAlign.Center)
样例运行结果如下图所示:
maxLines|textOverflow
设置文本显示的最大行数和截取方式,默认折行显示不截取,如果设置了此参数,则文本最多显示到指定的行,如果有多余的文本,可以通过 textOverflow 来指定截取方式,本样例的截断方式是 Ellipsis ,它将截断后的文本用 "..." 表示。
bash
Text('Hello, OpenHarmony, Hello, OpenHarmony, Hello, OpenHarmony, Hello, OpenHarmony')
Text('Hello, OpenHarmony, Hello, OpenHarmony, Hello, OpenHarmony, Hello, OpenHarmony')
.margin({top: 5})
.maxLines(1)
.textOverflow({overflow: TextOverflow.Ellipsis})
样例运行结果如下图所示:
fontSize、fontColor、fontStyle、 fontWeight:
分别表示设置文字的大小,颜色,样式以及粗细,我们可以组合起来设置文本的富样式,先看一个样例:
bash
Text('Hello, OpenHarmony')
Text('Hello, OpenHarmony')
.fontSize(20)
.fontColor('#ff0000')
.fontWeight(FontWeight.Bold)
.fontStyle(FontStyle.Italic)
.decoration({type: TextDecorationType.Underline, color: Color.Black})
样例运行结果如下图所示:
本样例中使用的 decoration
表示给文本添加装饰线,本样例使用的样式为 Underline
,其它样式请读者自行查看文档介绍。