> 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-es/scenes-sdk7/ui-2d/ui_background.md).

# Fondo de UI

Establece un fondo y un borde de una entidad de UI.

Las siguientes properties se usan para establecer un background y un border en una UI entity.

## Background

Un `uiBackground` component da color o una texture al área de una entity. Usa el size y la position definidos por la entity `uiTransform`.

Se pueden configurar los siguientes fields, todos son optional:

* `color`: El color a usar en la entity, como un value de [Color4](/creator/content-creator-es/scenes-sdk7/fundamentos-del-contenido-3d/color-types.md) color.

{% hint style="info" %}
**💡 Consejo**: Haz una entity semitransparente estableciendo el cuarto value de la `Color4` a menos de 1.
{% endhint %}

* `texture`: La texture a mostrar en la entity; esto toma un object con varios parameters sobre la texture. Las mismas properties están disponibles que en textures en [materials en 3D entities](/creator/content-creator-es/scenes-sdk7/fundamentos-del-contenido-3d/materials.md#using-textures).

  * `src`: La path al archivo de image a usar como texture. (string)

  * `filterMode`: *(opcional)* Determina cómo se estiran o comprimen los pixels de la texture cuando se renderizan. . Ver [Texture Scaling](/creator/content-creator-es/scenes-sdk7/fundamentos-del-contenido-3d/materials.md#texture-scaling). (FilterMode = 'point' | 'bi-linear' | 'tri-linear')

  * `wrapMode`: *(opcional)* Determina cómo se tesela una texture sobre una entity. Esto toma un value del `TextureWrapMode` enum. Ver \[Texture Wrapping]\([Ver documentación](https://github.com/decentraland/docs/tree/main/creator/sdk7/README.md)). (WrapMode = 'repeat' | 'clamp' | 'mirror')

  > Consejo: puedes combinar ambas `texture` y `color` properties en un solo `uiBackground` component para producir una texture tintada.
* `textureMode`: Selecciona cómo quieres que la texture se adapte al size de la entity a la que se aplica. (TextureMode = 'nine-slices' | 'center' | 'stretch')enum, que admite los siguientes values:
  * `center`: La texture no se estira; se centra en la entity y partes de ella pueden recortarse según el size de la entity.
  * `stretch`: La texture se estira para coincidir con toda la surface de la entity.
  * `nine-slices`: Partes de la texture se estiran para coincidir con toda la surface de la entity, dejando los margins sin estirar. Ver [nine-slice textures](#nine-slice-textures).
* `avatarTexture`: Muestra una miniatura del perfil de un avatar, basada en un avatar ID. Ver \[Avatar Portraits]\(([Ver documentación](https://github.com/decentraland/docs/tree/main/creator/sdk7/README.md)).
* `textureSlices`: Determina los margins que se usarán al usar el modo de texture nine-slice, ver [nine-slice textures](#nine-slice-textures). Establece un number menor que 1, como fracción del ancho o alto total de la image.

Simple color:

***Archivo 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)
	}}
  />
)
```

***Archivo 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" %}
**📔 Nota**: Todos los siguientes fragmentos de esta página asumen que tienes un `.ts` similar al anterior, ejecutando la `ReactEcsRenderer.setUiRenderer()` función.
{% endhint %}

Repeated texture pattern:

```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'
		}
	}}
  />
)
```

## Borders

Se usan algunas properties para establecer un border alrededor de una UI entity. Estas properties existen en el `uiTransform` component. Cada una te permite establecer un único value para todos los sides del border, o values diferentes para cada side.

* `borderColor`: El color a usar en la entity, como un value de [Color4](/creator/content-creator-es/scenes-sdk7/fundamentos-del-contenido-3d/color-types.md) color.
* `borderWidth`: El width del border, como un number en pixels. También admite values en percentages, por ejemplo `borderWidth: '2%'` establecerá el width del border al 2% del width de la entity.
* `borderRadius`: Usa esta property para darle a las corners de la entity un border redondeado. Establece el radius de las corners en pixels.

```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` y `borderRadius` también puede establecerse con values diferentes para cada side de la entity.

```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

Usa el `opacity` property en el `uiTransform` de una `UiEntity` para añadir transparency a la entity y a todos sus children. La property opacity es un value de 0 a 1, donde 0 es totalmente transparente y 1 totalmente opaco.

```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: "Este texto también es transparente",
          fontSize: 40
        }}
      />
   </UiEntity>
)
```

El value de opacity afecta a todos los children de una UiEntity, aplicando transparency a los background colors, text colors y background images. Cuando tanto el parent como un child tienen values de opacity, la opacity final del child es el product de su propio value y el del parent.

```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: "Este texto es aún más transparente",
        fontSize: 40
      }}
    />
  </UiEntity>
)
```

## Nine-slice textures

Puedes usar [9-slice scaling](https://en.wikipedia.org/wiki/9-slice_scaling) con tus textures, para asegurarte de que las corners y los margins no se estiren de forma desigual.

Con esta popular técnica, divides una image en 9 segments, que se estirarán de distintas maneras para preservar las proportions de los margins y las corners. Por example, úsala para definir backgrounds con corners redondeadas que se adapten fácilmente a cualquier size. Considera la siguiente image (tomada de [Wikipedia](https://en.wikipedia.org/wiki/9-slice_scaling#/media/File:Traditional_scaling_vs_9-slice_scaling.svg)):

![](https://1216664193-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-e2ac050bd4fa39a8b191cd36e282279f43613058%2F9-slice.png?alt=media\&token=097c41d5-86f7-4f0d-ba53-bac14132c9e7)

En esta image vemos la original texture (top-left), y el result de escalarla de manera traditional (top-right); observa cómo se deforman las corners. Debajo, vemos la texture segmentada en 9 slices (bottom-left), y luego el result de estirar la image según el método 9-slice (bottom-right).

Así es como se ve afectado cada segment, usando la image anterior como reference.

* El segment 5 es la única parte de la image que se estira completamente en ambos ejes x y e y.
* Los segments 1,3, 7 y 9 (las corners) no se estiran en absoluto.
* Los segments 2 y 8 solo se estiran horizontalmente
* Los segments 4 y 6 solo se estiran verticalmente.

Para usar el estiramiento nine-slice en una entity, setea el `textureMode` en `'nine-slices'`. Opcionalmente, también puedes establecer un width para el margin en cada side en `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
      }
	}}
  />
)
```

## Texture UVs

Usa el `uvs` property en un `uiBackground` component para mostrar una región específica de una texture. Esto es útil para tomar sprites individuales de un sprite sheet, o para rotar una image.

El `uvs` field toma un array de 8 numbers, que representa 4 pares de coordenadas UV para las cuatro corners de la región de la texture. El orden es: **bottom-left**, **top-left**, **top-right**, **bottom-right**. Cada value va de 0 a 1, donde `(0, 0)` es la esquina bottom-left de la image y `(1, 1)` es la top-right.

{% hint style="info" %}
**💡 Consejo**: Cuando uses custom `uvs`, establece `textureMode` en `'stretch'` para que la región seleccionada llene el área de la entity.
{% endhint %}

### Sprites from a sprite sheet

Para mostrar una porción de una image más grande (por example, una card de un sprite sheet que contiene varias), setea el `uvs` a las coordinates de esa region.

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

// Muestra la mitad izquierda de una texture (p. ej., la primera card en un sprite sheet de 2 columns)
export const uiMenu = () => (
  <UiEntity
    uiTransform={{ width: 200, height: 300 }}
    uiBackground={{
      textureMode: 'stretch',
      texture: { src: 'images/card-atlas.png' },
      uvs: [
        // bottom-left, top-left, top-right, bottom-right
        0, 0,
        0, 1,
        0.5, 1,
        0.5, 0
      ]
    }}
  />
)
```

Para un sprite sheet con una grid de frames (por example, un sheet de 4 columns por 2 rows), calcula los UVs basándote en la column y la row del frame que quieres:

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

// Elige un frame individual de un sprite sheet en grid
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
  ]
}

// Muestra la column 2, row 0 de un sprite sheet 4x2
export const uiMenu = () => (
  <UiEntity
    uiTransform={{ width: 128, height: 128 }}
    uiBackground={{
      textureMode: 'stretch',
      texture: { src: 'images/spritesheet.png' },
      uvs: getFrameUVs(2, 0, 4, 2)
    }}
  />
)
```

### Rotating an image with UVs

Puedes rotar una texture aplicando una rotación 2D a las coordenadas UV. Esto es útil para spinners o loading indicators sin necesidad de rotación basada en Transform.

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

// Rota un point 2D alrededor de un center
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
  ]
}

// Construye UV coordinates rotadas
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

// System que actualiza el angle en cada frame
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)
    }}
  />
)
```

El `rotateUVs` function rota las cuatro UV corners alrededor del punto center `(0.5, 0.5)` con el angle dado en radians. Como esto se llama en cada frame por el renderer similar a React, el spinner se actualiza suavemente.

{% hint style="info" %}
**💡 Consejo**: Ver un example completo y funcional con sprites, sprite sheets animados, spinners y más en la [UI Animations](https://github.com/decentraland/sdk7-goerli-plaza/tree/main/ui-animations) example scene.
{% 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-es/scenes-sdk7/ui-2d/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.
