本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新
一、基础属性
API | 类型/枚举 | 示例 | 说明 | 版本 |
---|
minFontSize | number | .minFontSize(12) | 最小自适应字号 | API 9+ |
maxFontSize | number | .maxFontSize(24) | 最大自适应字号 | API 9+ |
baselineOffset | Length | .baselineOffset(5) | 基线偏移量(正数上移) | API 10+ |
textIndent | Length | .textIndent(20) | 首行缩进 | API 10+ |
strikeThrough | { thickness?: number, color?: ResourceColor } | .strikeThrough({ thickness: 2, color: Color.Red }) | 删除线定制 | API 12+ |
二、高级布局控制
1. 文本测量(API 12+)
// 获取文本行数
Text('多行文本').onAreaChange((oldVal, newVal) => {
const lineCount = newVal.height / lineHeight; // 动态计算行数
})
// 使用LayoutManager获取精确信息
const layoutManager = this.textController.getLayoutManager();
const lineMetrics = layoutManager.getLineMetrics(0); // 获取首行信息
返回值对象:
interface LineMetrics {
width: number; // 行宽(px)
ascent: number; // 字体顶部到基线的距离
descent: number; // 字体底部到基线的距离
}
2. 文本选区(API 11+)
Text('可选中文本')
.textSelection(true) // 启用选区
.copyOption(CopyOptions.Local) // 允许复制到本地
.onSelectionChange((start, end) => { // 选区变化回调
console.log(`选中范围: ${start}-${end}`);
})
三、交互与动画
1. 手势事件扩展
API | 说明 | 示例 |
---|
onLongPress | 长按事件 | .onLongPress(() => this.showMenu()) |
onHover | 悬停效果 | .onHover((isHover) => this.bgColor = isHover ? '#EEE' : 'white') |
onDragStart | 拖拽开始 | .onDragStart(() => this.captureText()) |
2. 复合动画
@State rotate: number = 0;
@State scale: number = 1;
Text('动态文本')
.rotate({ angle: this.rotate })
.scale({ x: this.scale, y: this.scale })
.onClick(() => {
animateTo({ duration: 1000 }, () => {
this.rotate = 360;
this.scale = 1.5;
})
})
四、国际化与无障碍
1. 多语言动态切换
// string.json定义多语言
{ "hello": { "zh": "你好", "en": "Hello" } }
// 代码动态切换
@State locale: string = 'en';
Text($r(`app.string.hello.${this.locale}`))
2. 无障碍支持
Text('重要提示')
.accessibilityText("这是关键操作提示") // 读屏专用描述
.accessibilityLevel(AccessibilityLevel.Important)
五、性能优化相关API
1. 渲染控制
Text(largeText)
.cachedCount(5) // 复用相邻文本节点
.reuseId('text1') // 指定复用标识
2. 异步绘制
Text('复杂渲染文本')
.asyncRender(true) // 启用离屏渲染
.onRenderDone(() => console.log('渲染完成'))
六、高级示例:图文混排
Text() {
Span('点击')
.fontColor(Color.Blue)
.onClick(() => this.openLink())
ImageSpan($r('app.media.icon'))
.width(20)
.height(20)
Span('查看详情')
}
.fontSize(16)
.decoration({ type: TextDecorationType.Underline })
七、新增 API 版本适配表
功能 | 支持版本 | 元服务/卡片 |
---|
基线偏移 | API 10+ | 仅元服务 |
文本选区 | API 11+ | 支持卡片 |
LayoutManager | API 12+ | 仅元服务 |
异步渲染 | API 12+ | 不支持卡片 |