> 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 实体中写入文本。

通过创建一个 `Label` 实体，从玩家摄像机位置向前追踪一条射线。

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

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

  > 注意：该 `字体大小` 不受其实体或父实体大小的影响。
* `颜色`：文本颜色，作为一个 [Color4](/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/color-types.md).
* `字体`：要使用的字体。支持的值有：
  * `'serif'`
  * `'sans-serif'` *（默认）*
  * `'monospace'`
* `文本对齐`：文本如何与其父级对齐。它取自以下类型的值： `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 文本中使用表情符号

在任何 `Label` 或 `按钮` `值`, `uiText.value`, `输入框` `占位符`，以及 `下拉框` 选项。

SDK 不包含表情符号字形。表情符号是否显示取决于每个浏览器捆绑的字体，而 Unity 浏览器没有这些字体，因此字符会显示为空框或完全消失。同样的注意事项也适用于其他装饰性 Unicode 字符，例如箭头和框线字符。

如果要做图形标签，请改用图像：把图片放在一个小的 `UiEntity` 中，放在文本旁边，使用一个 `uiBackground` 并配合一个 `纹理`。见 [UI 背景](/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: '你好，世界！',
			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: '你好，世界！',
      fontSize: scaleFontSize(15)
    }}
  />
)
```

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

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

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

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

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

```ts
final font = 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: '你好，世界！',
      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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
