> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/2d-ui/ui_text.md).

# UI 文本

在 UI 实体中写入文本。

通过创建一个来向你的 UI 添加文本 `Label` 实体，从玩家摄像机位置向前追踪一条射线。

一个 `Label` 实体具有以下可配置字段：

* `value`: 要显示的字符串
* `字体大小`：文本大小，以数字表示。

  > 注意： `字体大小` 不受其实体或父实体大小的影响。
* `color`: 文本的颜色，作为一个 [Color4](/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/color-types.md).
* `font`: 要使用的字体。支持的值有：
  * `'serif'`
  * `'sans-serif'` *（默认）*
  * `'monospace'`
* `textAlign`: 文本将如何与其父级对齐。它取自以下的 `TextAlignType` 类型。TextAlignType = 'top-left' | 'top-center' | 'top-right' | 'middle-left' | 'middle-center' | 'middle-right' | 'bottom-left' | 'bottom-center' | 'bottom-right';
* `textWrap`: 设置文本是否使用换行来防止超过最大宽度。默认启用（`'wrap'`），要停用它请传入值 `'nowrap'`.

{% hint style="warning" %}
**📔 注意**：该 `字体大小` 不受其实体或父实体大小的影响。
{% endhint %}

一个 `Label` 实体也可以拥有其他类型 UI 实体中常见的组件，例如 `uiTransform` 和 `uiBackground`.

***ui.tsx 文件：***

```ts
import { UiEntity, Label, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'

export const uiMenu = () => (
	<UiEntity uiTransform={{ width: 'auto', height: 'auto' }}>
		<Label
			value="这是一个标签"
			color={Color4.Red()}
			fontSize={29}
			font="sans-serif"
			textAlign="top-left"
		/>
	</UiEntity>
)
```

***index.ts 文件：***

```ts
import { ReactEcsRenderer } from '@dcl/sdk/react-ecs'
import { uiMenu } from './ui'

export function main() {
    ReactEcsRenderer.setUiRenderer(uiMenu, { virtualWidth: 1920, virtualHeight: 1080 })
}
```

{% hint style="warning" %}
**📔 注意**：本页下面的所有代码片段都假设你有一个 `.ts` 类似于上面的内容，正在运行 `ReactEcsRenderer.setUiRenderer()` 函数。
{% endhint %}

如果某一行文本过长，无法放入分配的宽度或其容器的最大宽度中，文本会继续到下一行。你可以通过更改以下项的值来禁用此功能： `textWrap` 属性设为 `'nowrap'`.

你也可以通过显式添加 `\n` 到字符串中来强制换行。

```ts
import { UiEntity, Label, ReactEcs } from '@dcl/sdk/react-ecs'

export const uiMenu = () => (
	<UiEntity uiTransform={{ width: 700, height: 400 }}>
		<Label 
			value="你好，世界！\n这另一部分相当长。它很可能无法放在单行中，因此会在某处换行。\n第四行"
			textWrap= {`nowrap`} 
		/>
	</UiEntity>
)
```

如果没有显式 `height` 或 `width` 设置在 `uiTransform` 容器中的该项，容器将使用值 `auto`，它会调整以适应所有文本。你可以设置一个 `maxWidth` 以及一个 `maxHeight` 来确保它不会超出某些限制。你也可以使用 `minWidth` 和 `minHeight` 来确保容器不会变得过小，即使文本更短也是如此。

{% hint style="warning" %}
**📔 注意**: 不要依赖文本的自动适配。一个 `Label` 在你未设置其大小时占用多少空间，各个浏览器并不相同。基于 Bevy 的浏览器会测量渲染后的文本并据此布局。Unity 浏览器几乎不给它任何高度，但仍然会绘制字母，所以堆叠的标签会彼此重叠，而一个按文本尺寸设置大小的父级会塌缩为空。

为每个 `Label` 显式的 `width` **和** `height` 在其 `uiTransform`，并为任何堆叠标签的容器设置显式高度。对于换行文本，请根据行数设置高度：两行在 `fontSize: 20` 大约需要 `height: 60`.

由于不同浏览器的实现不同，在一个客户端里看起来正确的预览，并不能证明在另一个客户端中布局也是正确的。
{% endhint %}

## 不要在 UI 文本中使用 emoji

在任何 `Label` 或 `Button` `value`, `uiText.value`, `输入` `占位符`、以及 `下拉菜单` 选项。

SDK 不包含 emoji 字形。emoji 是否显示取决于各浏览器打包的字体，而 Unity 浏览器没有，所以字符会显示为空框或完全消失。对箭头和制表框线字符等其他装饰性 Unicode 字符也适用同样的注意事项。

对于图示标签，请改为提供图像：在一个小的 `UiEntity` 放在文本旁边，使用一个 `uiBackground` 搭配一个 `纹理`。参见 [UI Backgrounds](/creator/content-creator-zh/chang-jing-sdk7/2d-ui/ui_background.md).

```ts
import { UiEntity, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'

export const uiMenu = () => (
	<UiEntity
		uiTransform={{
			minWidth: 100,
			maxWidth: 300,
			height: 'auto',
			alignSelf: 'center',
			padding: 10,
		}}
		uiBackground={{
			color: Color4.Red(),
		}}
		uiText={{
			value: 'Hello world!',
			fontSize: 18,
		}}
	/>
)
```

## 响应式文本大小

使用 `scaleFontSize()` 函数，用于提供会根据玩家屏幕大小调整的字体值。在设置 `字体大小` 文本 UI 实体的属性时，请传入这个函数，而不是单个数字。

```ts
import { scaleFontSize } from '@dcl/sdk/react-ecs'
import { UiEntity, ReactEcs } from '@dcl/sdk/react-ecs'
import { Color4 } from '@dcl/sdk/math'

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
      width: 'auto',
      height: 'auto',
      alignSelf: 'center',
      padding: 10,
    }}
    uiText={{
      value: 'Hello world!',
      fontSize: scaleFontSize(15)
    }}
  />
)
```

该 `scaleFontSize()` 函数需要两个参数：

* `字体大小`: 要使用的基础字体大小。
* `scaleUnit` *（可选）*: 缩放系数。它决定文本应根据屏幕宽度还是高度进行调整，以及调整的倍率。默认值： `0.39` （一个数字，因此会被解释为相对于 *width*）。可取的值有：
  * *数字*: 一个简单数字，在这种情况下会被解释为相对于 *width*
  * *以……结尾的字符串 **vw***: 这会使数字相对于视图宽度。比如 `"0.8vw"`
  * *以……结尾的字符串 **vh***: 这会使数字相对于视图高度。比如 `"0.8vh"`

{% hint style="info" %}
**💡 提示**: 此函数的工作方式类似于 CSS 的 `calc()` 函数。
{% endhint %}

……的值 `scaleUnit` 是窗口宽度或高度的百分比。因此 `scaleUnit` 为 `"100vw"` 表示屏幕宽度的 100%，而值 `"0.5vw"` 表示屏幕宽度的 0.5%。

其公式 `scaleFontSize()` 如下：它将屏幕宽度或高度乘以 `scaleUnit`，然后再加上 `字体大小` 第一个参数传入的值。

```ts
最终字体 = fontSize + (screen width * scaleUnit / 100)
```

例如，下面的代码片段使用了一个 `scaleUnit` 值为 0.8。如果屏幕宽度是 *1280px*，则会得到大小为 **25.24**，遵循如下公式 `15 + (1280 * 0.8 / 100)`.

{% hint style="warning" %}
**📔 注意**: `scaleFontSize()` 返回一个 **数值**，因此其结果是一个以 *虚拟* 像素——它在绘制前仍会乘以 [UI 缩放因子](/creator/content-creator-zh/chang-jing-sdk7/2d-ui/onscreen-ui.md#screen-virtual-scale) 后再绘制。在上面的示例中，使用默认的 `1920x1080` 虚拟屏幕和一个宽度为 1280px 的画布，缩放因子为 `1280 / 1920 = 0.667`，因此文本渲染出来大约是 16.8px。如果你想要直接按画布测量、忽略虚拟屏幕的字体大小，请传入一个 `vw`/`vh` **字符串** 直接传给 `字体大小` 来代替——例如 `fontSize: '1.8vh'`.
{% endhint %}

```ts
import { scaleFontSize } from '@dcl/sdk/react-ecs'
import { UiEntity, ReactEcs } from '@dcl/sdk/react-ecs'

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
      width: 'auto',
      height: 'auto',
      alignSelf: 'center',
      padding: 10,
    }}
    uiText={{
      value: 'Hello world!',
      fontSize: scaleFontSize(15, 0.8)
    }}
  />
)
```

{% hint style="info" %}
**💡 提示**: 如果你没有不同屏幕尺寸可供测试，可以尝试使用 Web Explorer，并调整运行预览的窗口大小。每次你更改窗口时，文本都会立即调整。
{% endhint %}

作为……的替代方案 `scaleFontSize()`，请传入一个 `vw`/`vh` 直接将字符串作为 `字体大小` ——例如 `fontSize: '1.8vh'` ——它会根据画布来设置文本大小，并完全忽略 UI 缩放因子。不要 **不是** 将字体大小乘以你自己根据 `UiCanvasInformation`: SDK 已经会应用一个，参见 [响应式 UI 大小](/creator/content-creator-zh/chang-jing-sdk7/2d-ui/ui-positioning.md#responsive-ui-size).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/2d-ui/ui_text.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
