跳转到内容

文本与图片

Text

通过 TextPlugin 自动将样式化文本渲染为 Sprite 纹理。

设置: 在实体上添加 TransformSpriteUIRectText

属性类型默认值说明
contentstring''文本内容
fontFamilystring'Arial'字体名称
fontSizenumber24字号(像素)
colorColor{r:1, g:1, b:1, a:1}文本颜色 RGBA
alignTextAlignLeftLeft (0)、Center (1)、Right (2)
verticalAlignTextVerticalAlignTopTop (0)、Middle (1)、Bottom (2)
wordWrapbooleantrue启用自动换行
overflowTextOverflowVisibleVisible (0)、Clip (1)、Ellipsis (2)
lineHeightnumber1.2行高倍率
richTextbooleanfalse启用富文本解析
strokeColorColor{r:0, g:0, b:0, a:0}文本描边颜色
strokeWidthnumber0文本描边宽度(像素)
shadowColorColor{r:0, g:0, b:0, a:0.5}投影颜色
shadowBlurnumber0投影模糊半径
shadowOffsetXnumber0投影水平偏移
shadowOffsetYnumber0投影垂直偏移

运行时修改文本

import { defineSystem, addSystem, Query, Mut, Text } from 'esengine';
addSystem(defineSystem(
[Query(Mut(Text))],
(query) => {
for (const [entity, text] of query) {
text.content = '已更新!';
text.fontSize = 32;
}
}
));

富文本

启用 richText 属性以使用内联格式标签:

text.richText = true;
text.content = '<color=#FF0000>红色</color>和<b>粗体</b>文本';

支持的标签:

标签说明示例
<color=#RRGGBB>文本颜色<color=#FF0000>红色</color>
<b>粗体<b>粗体文本</b>
<i>斜体<i>斜体文本</i>
<img src="path"/>内联图片<img src="icons/star.png"/>

标签可以嵌套:<color=#00FF00><b>绿色粗体</b></color>

描边与投影

为任意文本添加描边和投影效果:

// 描边
text.strokeColor = { r: 0, g: 0, b: 0, a: 1 };
text.strokeWidth = 2;
// 投影
text.shadowColor = { r: 0, g: 0, b: 0, a: 0.5 };
text.shadowBlur = 4;
text.shadowOffsetX = 2;
text.shadowOffsetY = 2;

描边和投影同时适用于普通文本和富文本。在富文本模式下,描边能够正确渲染所有文本片段(所有描边在填充之前绘制,以防止视觉重叠)。

Image

显示图片,支持切片、平铺和填充模式。

属性类型默认值说明
texturenumber纹理资产句柄
colorColor{r:1, g:1, b:1, a:1}颜色着色
imageTypeImageTypeSimpleSimple (0)、Sliced (1)、Tiled (2)、Filled (3)
fillMethodFillMethodHorizontalHorizontal (0)、Vertical (1)
fillOriginFillOriginLeftLeft (0)、Right (1)、Bottom (2)、Top (3)
fillAmountnumber1填充进度 0–1
preserveAspectbooleanfalse保持宽高比
tileSizeVec2{x:32, y:32}平铺尺寸(imageTypeTiled 时使用)
layernumber0渲染层级
materialnumber0自定义材质句柄(0 = 默认)
enabledbooleantrue可见性开关

示例:分数显示

import { defineTag, defineComponent, defineSystem, addSystem, Query, Mut, Changed, Text } from 'esengine';
const ScoreDisplay = defineTag('ScoreDisplay');
const GameState = defineComponent('GameState', { score: 0 });
addSystem(defineSystem(
[Query(Mut(Text), ScoreDisplay), Query(Changed(GameState))],
(displays, stateQuery) => {
if (stateQuery.isEmpty()) return;
const [, state] = stateQuery.single()!;
for (const [, text] of displays) {
text.content = `分数:${state.score}`;
}
}
));

使用变更检测,仅在分数实际变化时更新文本。

下一步

  • UI 布局 — 锚点、Flex 和网格布局
  • 交互 — 指针事件、焦点和拖拽
  • 位图文本 — GPU 渲染的位图字体文本
  • 精灵 — 精灵渲染详情