# Formas

- Human documentation: [https://docs.univer.ai/es-ES/guides/sheets/features/shapes](https://docs.univer.ai/es-ES/guides/sheets/features/shapes)

- Agent Markdown: [https://docs.univer.ai/es-ES/guides/sheets/features/shapes.md](https://docs.univer.ai/es-ES/guides/sheets/features/shapes.md)

- Requested language: `es-ES`

- Content language: `es-ES`

- Documentation version: `1.2.0`

- Source: [sheets/features/shapes.es-ES.mdx](https://github.com/dream-num/documentation/blob/dev/content/guides/sheets/features/shapes.es-ES.mdx)

---

#### Package metadata

```json
{
  "mobile": true,
  "preset": [
    {
      "client": "@univerjs/preset-sheets-advanced",
      "locale": "@univerjs/preset-sheets-advanced/locales/en-US",
      "style": "@univerjs/preset-sheets-advanced/lib/index.css"
    }
  ],
  "plugins": [
    {
      "client": "@univerjs-pro/engine-formula"
    },
    {
      "client": "@univerjs/drawing"
    },
    {
      "client": "@univerjs/drawing-ui",
      "locale": "@univerjs/drawing-ui/locale/en-US",
      "style": "@univerjs/drawing-ui/lib/index.css"
    },
    {
      "client": "@univerjs/sheets-drawing"
    },
    {
      "client": "@univerjs/sheets-drawing-ui",
      "locale": "@univerjs/sheets-drawing-ui/locale/en-US",
      "style": "@univerjs/sheets-drawing-ui/lib/index.css"
    },
    {
      "client": "@univerjs-pro/sheets-shape"
    },
    {
      "client": "@univerjs-pro/sheets-shape-ui",
      "facade": "@univerjs-pro/sheets-shape/facade",
      "locale": "@univerjs-pro/sheets-shape-ui/locale/en-US",
      "style": "@univerjs-pro/sheets-shape-ui/lib/index.css"
    }
  ],
  "license": true,
  "server": false
}
```

Las formas en Univer Sheets se pueden usar para crear diagramas de flujo, anotaciones, llamadas y guías visuales directamente en hojas de trabajo.

> Interactive example: [Open the playground](/playground/sheets/shapes)

## Modo de complemento

### Instalación

#### npm

```bash
npm install @univerjs-pro/engine-formula @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui @univerjs-pro/sheets-shape @univerjs-pro/sheets-shape-ui
```

#### pnpm

```bash
pnpm add @univerjs-pro/engine-formula @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui @univerjs-pro/sheets-shape @univerjs-pro/sheets-shape-ui
```

#### yarn

```bash
yarn add @univerjs-pro/engine-formula @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui @univerjs-pro/sheets-shape @univerjs-pro/sheets-shape-ui
```

#### bun

```bash
bun add @univerjs-pro/engine-formula @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui @univerjs-pro/sheets-shape @univerjs-pro/sheets-shape-ui
```

> [!WARN]
> Las formas también requieren `UniverProFormulaEnginePlugin` del paquete `@univerjs-pro/engine-formula`. En el código de inicialización base, sustituya la importación y el registro de `UniverFormulaEnginePlugin` por este plugin. No registre ambos motores de fórmulas, ya que la inserción de formas podría fallar por una dependencia no registrada.
> 
> Los complementos de formas dependen de los complementos de dibujo. También debe registrar `UniverDrawingPlugin`, `UniverSheetsDrawingPlugin`, `UniverDrawingUIPlugin` y `UniverSheetsDrawingUIPlugin` antes de registrar los complementos de formas.

### Uso

```typescript
import { UniverProFormulaEnginePlugin } from '@univerjs-pro/engine-formula' // [!code ++]
import { UniverSheetsShapePlugin } from '@univerjs-pro/sheets-shape' // [!code ++]
import { UniverSheetsShapeUIPlugin } from '@univerjs-pro/sheets-shape-ui' // [!code ++]
import SheetsShapeUIEnUS from '@univerjs-pro/sheets-shape-ui/locale/en-US' // [!code ++]
import { LocaleType, mergeLocales, Univer } from '@univerjs/core'
import { UniverDrawingPlugin } from '@univerjs/drawing' // [!code ++]
import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui' // [!code ++]
import DrawingUIEnUS from '@univerjs/drawing-ui/locale/en-US' // [!code ++]
import { UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing' // [!code ++]
import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui' // [!code ++]
import SheetsDrawingUIEnUS from '@univerjs/sheets-drawing-ui/locale/en-US' // [!code ++]

import '@univerjs-pro/sheets-shape/facade' // [!code ++]

import '@univerjs/drawing-ui/lib/index.css' // [!code ++]
import '@univerjs/sheets-drawing-ui/lib/index.css' // [!code ++]
import '@univerjs-pro/sheets-shape-ui/lib/index.css' // [!code ++]

const univer = new Univer({
  locale: LocaleType.EN_US,
  locales: {
    [LocaleType.EN_US]: mergeLocales(
      DrawingUIEnUS, // [!code ++]
      SheetsDrawingUIEnUS, // [!code ++]
      SheetsShapeUIEnUS, // [!code ++]
    ),
  },
})

univer.registerPlugin(UniverProFormulaEnginePlugin) // [!code ++]
univer.registerPlugin(UniverDrawingPlugin) // [!code ++]
univer.registerPlugin(UniverDrawingUIPlugin) // [!code ++]
univer.registerPlugin(UniverSheetsDrawingPlugin) // [!code ++]
univer.registerPlugin(UniverSheetsDrawingUIPlugin) // [!code ++]
univer.registerPlugin(UniverSheetsShapePlugin) // [!code ++]
univer.registerPlugin(UniverSheetsShapeUIPlugin) // [!code ++]
```

Si tiene una licencia comercial para Univer, consulte [Uso de la licencia en Client](https://docs.univer.ai/es-ES/server/license.md#in-plugin-mode) para la configuración.

## Compatibilidad móvil

Configure primero el [editor móvil](https://docs.univer.ai/es-ES/guides/sheets/getting-started/installation.md#mobile-support). En la inicialización en modo plugin de esta página, sustituya los registros de escritorio siguientes por las exportaciones móviles de los mismos paquetes **antes de abrir un documento**. Conserve modelos, estilos, traducciones e importaciones Facade; no registre ambas variantes.

| Paquete                         | Registro de escritorio        | Registro móvil                      |
| ------------------------------- | ----------------------------- | ----------------------------------- |
| `@univerjs/drawing-ui`          | `UniverDrawingUIPlugin`       | `UniverDrawingMobileUIPlugin`       |
| `@univerjs/sheets-drawing-ui`   | `UniverSheetsDrawingUIPlugin` | `UniverSheetsDrawingMobileUIPlugin` |
| `@univerjs-pro/sheets-shape-ui` | `UniverSheetsShapeUIPlugin`   | `UniverSheetsShapeMobileUIPlugin`   |

## Modo preestablecido

La función de forma está incluida en el ajuste preestablecido `@univerjs/preset-sheets-advanced`. Este ajuste preestablecido ya registra `UniverProFormulaEnginePlugin`, por lo que no es necesario sustituir manualmente el motor de fórmulas.

### Instalación

> [!NOTE]
> El ajuste preestablecido `UniverSheetsAdvancedPreset` de `@univerjs/preset-sheets-advanced` depende del `UniverSheetsDrawingPreset` preestablecido en tiempo de ejecución. Primero instale `@univerjs/preset-sheets-drawing`.

#### npm

```bash
npm install @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

#### pnpm

```bash
pnpm add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

#### yarn

```bash
yarn add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

#### bun

```bash
bun add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

### Uso

```typescript
import { UniverSheetsAdvancedPreset } from '@univerjs/preset-sheets-advanced' // [!code ++]
import UniverPresetSheetsAdvancedEnUS from '@univerjs/preset-sheets-advanced/locales/en-US' // [!code ++]
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'
import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'
import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing' // [!code ++]
import UniverPresetSheetsDrawingEnUS from '@univerjs/preset-sheets-drawing/locales/en-US' // [!code ++]
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'

import '@univerjs/preset-sheets-core/lib/index.css'
import '@univerjs/preset-sheets-drawing/lib/index.css' // [!code ++]
import '@univerjs/preset-sheets-advanced/lib/index.css' // [!code ++]

const { univerAPI } = createUniver({
  locale: LocaleType.EN_US,
  locales: {
    [LocaleType.EN_US]: mergeLocales(
      UniverPresetSheetsCoreEnUS,
      UniverPresetSheetsDrawingEnUS, // [!code ++]
      UniverPresetSheetsAdvancedEnUS, // [!code ++]
    ),
  },
  presets: [
    UniverSheetsCorePreset(),
    UniverSheetsDrawingPreset(), // [!code ++]
    UniverSheetsAdvancedPreset(), // [!code ++]
  ],
})
```

Si tiene una licencia comercial para Univer, consulte [Uso de licencia en el cliente](https://docs.univer.ai/es-ES/server/license.md#in-preset-mode) para la configuración.

## API de Facade

Las definiciones completas del tipo de API de Facade se pueden encontrar en [FacadeAPI](https://docs.univer.ai/es-ES/reference/facade/univer.md).

### Importar

> [!INFO: Plugin mode note]
> Sólo el modo complemento requiere importar manualmente el paquete Facade. El modo Preestablecido ya incluye el paquete Fachada correspondiente, por lo que no se necesita ninguna importación adicional.

```typescript
import '@univerjs-pro/sheets-shape/facade'
```

### Insertar formas básicas

Llama a `FWorksheet.insertShape` con los datos de creación comunes. Devuelve una fachada activa.

```typescript
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

const rectShape = fWorksheet.insertShape({
  shapeType: univerAPI.Enum.ShapeTypeEnum.Rect,
  transform: { left: 120, top: 80, width: 240, height: 120 },
  shapeData: {
    fill: {
      fillType: univerAPI.Enum.ShapeFillEnum.SolidFill,
      color: '#e6f4ff',
    },
    stroke: {
      lineStrokeType: univerAPI.Enum.ShapeLineTypeEnum.SolidLine,
      color: '#1677ff',
      width: 2,
    },
  },
})

if (!rectShape) throw new Error('Shape could not be inserted.')
```

### Editar el texto de una forma

Utiliza la forma devuelta por `insertShape()` a continuación o en el ejemplo anterior. `getText()` devuelve un objeto [FShapeText](https://docs.univer.ai/es-ES/reference/facade/shape-text.md) activo. Lee el texto con `getPlainText()`, reemplázalo por completo con `setText()` y configura la fuente, el color y la alineación.

```ts
if (!rectShape) throw new Error('Shape is not available')
const shapeText = rectShape.getText()
console.log(shapeText.getPlainText())
shapeText
  .setText('Quarterly review')
  .setFontSize(18)
  .setColor('#2563eb')
  .setBold(true)
  .setHorizontalAlign(univerAPI.Enum.HorizontalAlign.CENTER)
  .setVerticalAlign(univerAPI.Enum.VerticalAlign.MIDDLE)
```

`setText()` reemplaza el texto existente. Utiliza `setRichText()` para combinar varios estilos. Para editar texto enriquecido existente, llama a `getRichText()?.copy()`, modifica el constructor y pásalo a `setRichText()`. Los cambios del constructor no se aplican automáticamente. Consulta también los [estilos de texto](https://docs.univer.ai/es-ES/reference/facade/shape-text.md#settextstyle) y los [márgenes y la disposición del cuadro de texto](https://docs.univer.ai/es-ES/reference/facade/shape-text.md#settextboxoptions).

```ts
const richText = univerAPI.newRichText()
  .text('Quarterly ')
  .bold('review')
shapeText.setRichText(richText)
```

### Inserte y conecte formas de conector

Inserta un conector con `FWorksheet.insertShape` y vincula sus extremos mediante la fachada `FConnectorShape` devuelta.

```typescript
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

const leftShape = fWorksheet.insertShape({
  shapeType: univerAPI.Enum.ShapeTypeEnum.RoundRect,
  transform: { left: 80, top: 80, width: 180, height: 100 },
})
const rightShape = fWorksheet.insertShape({
  shapeType: univerAPI.Enum.ShapeTypeEnum.Ellipse,
  transform: { left: 420, top: 200, width: 180, height: 100 },
})
const connectorShape = fWorksheet.insertShape({
  shapeType: univerAPI.Enum.ShapeTypeEnum.BentConnector3,
  transform: { left: 240, top: 130, width: 240, height: 120 },
})

if (!leftShape || !rightShape || !connectorShape) {
  throw new Error('Shapes could not be inserted.')
}

const startSite = leftShape.getConnectionSites()[0]
const rightSites = rightShape.getConnectionSites()
const endSite = rightSites[2] ?? rightSites[0]

if (!startSite || !endSite) throw new Error('Connection site not found.')

connectorShape
  .bindStart(leftShape.getId(), startSite.index)
  .bindEnd(rightShape.getId(), endSite.index)
  .setEndArrow(univerAPI.Enum.ShapeArrowTypeEnum.Arrow)
```

### Actualizar y eliminar formas

Actualiza y elimina una forma directamente mediante su fachada activa.

```typescript
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()

const firstShape = fWorksheet.getShapes().find(shape => !shape.isConnectorShape())

if (firstShape) {
  firstShape
    .setStrokeColor('#ff4d4f')
    .setStrokeWidth(3)
    .setSolidFill('#fff1f0')

  // Remove the shape later if needed
  const removed = firstShape.remove()
  console.log(removed)
}
```

## Copiar formato de formas

Selecciona la forma original, activa el pincel y elige la forma de destino. Se copian relleno, contorno, efectos y formato de texto compatible, conservando identidad, geometría, contenido y vínculos de fórmulas del destino. Borrar formato restaura los valores de inserción. SmartArt queda excluido. El plugin UI correspondiente registra esta función automáticamente.
