> 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_background.md).

# UI 背景

设置 UI 实体的背景和边框。

以下属性用于为 UI 实体设置背景和边框。

## 背景

一个 `uiBackground` 组件用于为实体区域设置颜色或纹理。它使用实体 `uiTransform`.

可以配置以下字段，且全部为可选项：

* `color`：实体使用的颜色，值为 [Color4](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/color-types.md) 类型。

{% hint style="info" %}
**💡 提示**：将 `Color4` 的第 4 个值设为小于 1，即可使实体呈半透明。
{% endhint %}

* `texture`：要显示在实体上的纹理。该字段接受一个对象，其中包含纹理的各种参数。它提供的属性与 3D 实体 [材质中的纹理](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/materials.md#using-textures).

  * `src`：用作纹理的图像文件路径。（字符串）

  * `filterMode`: *（可选）* 决定渲染时如何拉伸或压缩纹理中的像素。另请参阅 [纹理缩放](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/materials.md#texture-scaling)。（FilterMode = 'point' | 'bi-linear' | 'tri-linear'）

  * `wrapMode`: *（可选）* 决定如何将纹理平铺到实体上。此字段接受 `TextureWrapMode` 枚举中的值。请参阅\[纹理环绕]\(([查看文档](https://github.com/decentraland/docs/tree/main/creator/sdk7/README.md)）。（WrapMode = 'repeat' | 'clamp' | 'mirror'）

  > 提示：你可以在同一个 `texture` 和 `color` 属性组合使用，添加到单个 `uiBackground` 组件上，从而生成着色纹理。
* `textureMode`：选择纹理适应所应用实体尺寸的方式。（TextureMode = 'nine-slices' | 'center' | 'stretch'）这是一个枚举，支持以下值：
  * `center`：纹理不会拉伸，而是居中显示在实体上；根据实体尺寸，纹理的部分内容可能会被裁切。
  * `stretch`：拉伸纹理，使其铺满实体的整个表面。
  * `nine-slices`：拉伸纹理的部分区域，使其铺满实体的整个表面，同时保持边缘不被拉伸。请参阅 [九宫格纹理](#nine-slice-textures).
* `avatarTexture`：根据头像 ID 显示头像资料缩略图。请参阅\[头像肖像]\(([查看文档](https://github.com/decentraland/docs/tree/main/creator/sdk7/README.md)).
* `textureSlices`：使用九宫格纹理模式时，用于确定边距；请参阅 [九宫格纹理](#nine-slice-textures)。设置一个小于 1 的数值，表示图像总宽度或总高度的比例。

纯色：

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

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

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
      width: 700,
      height: 400
    }}
    uiBackground={{
		color: Color4.create(0.5, 0.8, 0.1, 0.6)
	}}
  />
)
```

***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 %}

重复纹理图案：

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

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
      width: 700,
      height: 400
    }}
    uiBackground={{
		textureMode: 'center',
		texture: {
			src: "images/brick-wall-texture.png",
			wrapMode: 'repeat'
		}
	}}
  />
)
```

## 边框

可以使用几个属性为 UI 实体设置边框。这些属性位于 `uiTransform` 组件中。每个属性都支持为边框的所有边设置同一个值，也支持为每条边分别设置不同的值。

* `borderColor`：实体边框的颜色，值为 [Color4](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/color-types.md) 类型。
* `borderWidth`：边框宽度，以像素为单位。也支持百分比值，例如 `borderWidth: '2%'` 会将边框宽度设置为实体宽度的 2%。
* `borderRadius`：使用此属性可将实体的边角设为圆角。它以像素为单位设置边角半径。

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

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
      width: 700,
      height: 400,
      borderColor: Color4.Red(),
      borderWidth: 4,
      borderRadius: 10
    }}
  />
)
```

`borderWidth`, `borderColor` 和 `borderRadius` 也可以为实体的每条边分别设置不同的值。

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

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
      width: 700,
      height: 400,
      borderColor: { top: Color4.White(), left: Color4.Red(), right: Color4.Blue(), bottom: Color4.Gray() },
      borderRadius: { topLeft: 20, topRight: 20, bottomLeft: 20, bottomRight:0 },
      borderWidth: { top: 3, left: 2, right: 3, bottom: 4 }
    }}
  />
)
```

## 不透明度

使用 `opacity` 属性，在 `uiTransform` 中为 `UiEntity` 添加透明效果，该效果也会应用于实体的所有子项。opacity 属性的取值范围为 0 到 1，其中 0 表示完全透明，1 表示完全不透明。

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

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
      width: 700,
      height: 400,
      opacity: 0.7
    }}
    uiBackground={{ color: Color4.Green() }}
  >
    <UiEntity
        uiTransform={{
          width: 100,
          height: 30,
        }}
        uiText={{
          value: "This text is transparent too",
          fontSize: 40
        }}
      />
   </UiEntity>
)
```

透明度值会影响 UiEntity 的所有子级，使背景颜色、文本颜色和背景图像都变为透明。如果父级和子级都设置了透明度值，则子级的最终透明度是其自身透明度值与父级透明度值的乘积。

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

export const uiMenu = () => (
  <UiEntity
    uiTransform={{
      width: 700,
      height: 400,
      opacity: 0.7
    }}
    uiBackground={{ color: Color4.Green() }}
  >
    <UiEntity
      uiTransform={{
        width: 100,
        height: 30,
        opacity: 0.7
      }}
      uiText={{
        value: "This text is even more transparent",
        fontSize: 40
      }}
    />
  </UiEntity>
)
```

## 九宫格纹理

您可以对纹理使用 [九宫格缩放](https://en.wikipedia.org/wiki/9-slice_scaling) 以确保角落和边缘不会被不均匀地拉伸。

这种广受欢迎的技术会将图像切分为 9 个部分，并以不同方式拉伸这些部分，从而保留边缘和角落的比例。例如，您可以用它定义圆角背景，使其轻松适应任意尺寸。请看下面这张图片（引自 [维基百科](https://en.wikipedia.org/wiki/9-slice_scaling#/media/File:Traditional_scaling_vs_9-slice_scaling.svg)):

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-c07e3501f6f9fda01f510b0c0c237ea207d00e3d%2F9-slice.webp?alt=media)

在这张图片中，我们可以看到原始纹理（左上），以及以传统方式缩放后的结果（右上）；注意角落是如何变形的。下方则展示了切分为 9 个部分的纹理（左下），以及按照九宫格方法拉伸后的结果（右下）。

下面以这张图片为例，说明每个部分受到的影响。

* 只有部分 5 会在 x 轴和 y 轴上完全拉伸。
* 部分 1、3、7 和 9（角落）完全不会拉伸。
* 部分 2 和 8 只会水平拉伸。
* 第 4 和第 6 段仅进行垂直拉伸。

若要对实体使用九宫格拉伸，请将 `textureMode` 设置为 `'nine-slices'`。你还可以选择在 `textureSlices`.

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

export const uiMenu = () => (
  <UiEntity
    uiTransform={{ width: 700, height: 400 }}
    uiBackground={{
      textureMode: 'nine-slices',
      texture: {
        src: 'images/rounded_alpha_square.png'
      },
      textureSlices: {
        top: 0.2,
        bottom: 0.2,
        left: 0.2,
        right: 0.2
      }
	}}
  />
)
```

该 `textureSlices` 值是相对于 **纹理** 尺寸的分数，而非元素尺寸的分数。值为 `0.125` 在 128 像素的纹理上会生成 16 像素的圆角；无论元素是 100 像素的按钮还是 1,400 像素的面板，这些圆角始终宽 16 个虚拟像素。在桌面客户端中，圆角单元格不会随元素变大而放大。

因此，请根据屏幕上所需的圆角尺寸来设计美术资源：先确定圆角的虚拟像素尺寸，然后绘制纹理，使得 `textureSlices` × 纹理尺寸等于该数值。如果设计中按钮使用小圆角、面板使用大圆角，请为每种尺寸分别使用一张纹理，因为在同一图像上增大 `textureSlices` 并不会让圆角美术资源变大。

## 纹理 UV 坐标

使用 `uvs` 属性，设置在 `uiBackground` 用于显示纹理特定区域的组件。这适用于从精灵图集中选取单个精灵，或旋转图像。

&#x20;`uvs`  字段接受一个包含 8 个数字的数组，表示纹理区域四个角的 4 对 UV 坐标。顺序如下： **左下**, **左上**, **右上**, **右下**。每个值的范围为 0 到 1，其中 `(0, 0)` 表示图像的左下角， `(1, 1)` 表示右上角。

{% hint style="info" %}
**💡 提示**：使用自定义 `uvs`时，将 `textureMode` 设为 `'stretch'` ，使所选区域填满实体的区域。
{% endhint %}

### 从精灵图集中选取精灵

要显示较大图像的一部分（例如，包含多张卡片的精灵图集中的一张卡片），请将 `uvs` 设为该区域的坐标。

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

// 显示纹理的左半部分（例如，两列图集中的第一张卡片）
export const uiMenu = () => (
  <UiEntity
    uiTransform={{ width: 200, height: 300 }}
    uiBackground={{
      textureMode: 'stretch',
      texture: { src: 'images/card-atlas.png' },
      uvs: [
        // 左下、左上、右上、右下
        0, 0,
        0, 1,
        0.5, 1,
        0.5, 0
      ]
    }}
  />
)
```

对于按网格排列帧的精灵图集（例如，4 列 2 行的图集），请根据所需帧的列和行计算 UV 坐标：

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

// 从网格精灵图集中选取单帧
function getFrameUVs(col: number, row: number, totalCols: number, totalRows: number): number[] {
  const stepU = 1 / totalCols
  const stepV = 1 / totalRows
  const left = col * stepU
  const right = (col + 1) * stepU
  const top = 1 - row * stepV
  const bottom = 1 - (row + 1) * stepV
  return [
    left, bottom,
    left, top,
    right, top,
    right, bottom
  ]
}

// 显示 4x2 精灵图集中的第 2 列、第 0 行
export const uiMenu = () => (
  <UiEntity
    uiTransform={{ width: 128, height: 128 }}
    uiBackground={{
      textureMode: 'stretch',
      texture: { src: 'images/spritesheet.png' },
      uvs: getFrameUVs(2, 0, 4, 2)
    }}
  />
)
```

### 使用 UV 坐标旋转图像

你可以通过对 UV 坐标进行二维旋转来旋转纹理。这样无需使用基于变换的旋转，就能实现旋转器或加载指示器。

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

// 绕中心旋转二维点
function rotate2D(angle: number, x: number, y: number, cx: number, cy: number): number[] {
  const cos = Math.cos(angle)
  const sin = Math.sin(angle)
  return [
    cos * (x - cx) - sin * (y - cy) + cx,
    sin * (x - cx) + cos * (y - cy) + cy
  ]
}

// 构建旋转后的 UV 坐标
function rotateUVs(angle: number): number[] {
  const uv00 = rotate2D(angle, 0, 0, 0.5, 0.5)
  const uv01 = rotate2D(angle, 0, 1, 0.5, 0.5)
  const uv11 = rotate2D(angle, 1, 1, 0.5, 0.5)
  const uv10 = rotate2D(angle, 1, 0, 0.5, 0.5)
  return [uv00[0], uv00[1], uv01[0], uv01[1], uv11[0], uv11[1], uv10[0], uv10[1]]
}

let spinnerAngle = 0

// 每帧更新角度的系统
engine.addSystem((dt: number) => {
  spinnerAngle += dt * 5
})

export const uiMenu = () => (
  <UiEntity
    uiTransform={{ width: 128, height: 128 }}
    uiBackground={{
      textureMode: 'stretch',
      texture: { src: 'images/spinner.png' },
      uvs: rotateUVs(spinnerAngle)
    }}
  />
)
```

这个 `rotateUVs` 函数会根据给定的弧度角，绕中心点旋转四个 UV 角 `(0.5, 0.5)` 。由于类 React 渲染器会在每帧调用此函数，旋转图标可以平滑更新。

只有图片会旋转。元素本身、可点击区域、子元素和任何文本都保持原位。要实现干净的旋转效果，请注意以下几点：

* **保持元素为正方形**。如果盒子不是正方形，旋转后的图像会被挤压变形。
* **在图案周围留出透明边距**。旋转超过 45° 后，旋转区域的角会超出纹理范围，边缘像素会被拉伸到这些角上。请将图案放在正方形内切圆的范围内，并在周围留出透明像素。
* **在纹理中设置 `wrapMode: 'clamp'`** ，这样边缘会被拉伸，而不是重复： `texture: { src: 'images/spinner.png', wrapMode: 'clamp' }`.

{% hint style="info" %}
**💡 提示**：请参阅 [UI 动画](https://github.com/decentraland/sdk7-goerli-plaza/tree/main/ui-animations) 示例场景，了解包含精灵、动画精灵表、旋转图标等内容的完整可运行示例。
{% endhint %}


---

# 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_background.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.
