Imágenes
Las imágenes se pueden usar para enriquece el contenido de la hoja de cálculo, mejora la expresión visual y ayuda a ilustrar o resaltar información clave.
Actualmente, los tipos de imágenes admitidos son: imágenes flotantes e imágenes de celdas.
Modo predeterminado
Instalación
pnpm add @univerjs/preset-sheets-drawingnpm install @univerjs/preset-sheets-drawingyarn add @univerjs/preset-sheets-drawingbun add @univerjs/preset-sheets-drawingUso
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing'import UniverPresetSheetsDrawingEnUS from '@univerjs/preset-sheets-drawing/locales/en-US'import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'import '@univerjs/preset-sheets-core/lib/index.css'import '@univerjs/preset-sheets-drawing/lib/index.css'const { univerAPI } = createUniver({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: mergeLocales( UniverPresetSheetsCoreEnUS, UniverPresetSheetsDrawingEnUS, ), }, presets: [ UniverSheetsCorePreset(), UniverSheetsDrawingPreset(), ],})Si está utilizando la función Colaboración, asegúrese de pasar la opción collaboration: true en UniverSheetsDrawingPreset:
UniverSheetsDrawingPreset({ collaboration: true, })Preajustes y configuración
interface IUniverSheetsDrawingPresetConfig { /** * Whether use the collaboration feature. * @default false */ collaboration?: boolean /** * The maximum allowed size of uploaded images in bytes. * @default 5 * 1024 * 1024 (5MB) */ allowImageSize?: number}Modo de complemento
Instalación
pnpm add @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-uinpm install @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-uiyarn add @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-uibun add @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-uiUso
import { IImageIoService, LocaleType, mergeLocales, Univer } from '@univerjs/core'import { UniverDocsDrawingPlugin } from '@univerjs/docs-drawing'import { UniverDrawingPlugin } from '@univerjs/drawing'import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui'import DrawingUIEnUS from '@univerjs/drawing-ui/locale/en-US'import { UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing'import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui'import SheetsDrawingUIEnUS from '@univerjs/sheets-drawing-ui/locale/en-US'import '@univerjs/drawing-ui/lib/index.css'import '@univerjs/sheets-drawing-ui/lib/index.css'import '@univerjs/sheets-drawing/facade'import '@univerjs/sheets-drawing-ui/facade'const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: mergeLocales( DrawingUIEnUS, SheetsDrawingUIEnUS, ), },})univer.registerPlugin(UniverDrawingPlugin)univer.registerPlugin(UniverDrawingUIPlugin)univer.registerPlugin(UniverSheetsDrawingPlugin)univer.registerPlugin(UniverSheetsDrawingUIPlugin)Si está utilizando la función Colaboración, debe agregar la configuración override:
univer.registerPlugin(UniverDrawingPlugin, { override: [[IImageIoService, null]], // allowImageSize: 20 * 1024 * 1024, // set the maximum allowed size of uploaded images to 20MB, optional})Complementos y Configuración
interface IUniverDrawingConfig { /** * The maximum allowed size of uploaded images in bytes. * @default 5 * 1024 * 1024 (5MB) */ allowImageSize?: number}Compatibilidad móvil
Configure primero el editor móvil. 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 |
API de fachada
Las definiciones completas del tipo de API de Facade se pueden encontrar en FacadeAPI.
Importación
Plugin mode note
Solo el modo complemento requiere importar manualmente el paquete Facade. El modo preestablecido ya incluye el paquete Facade correspondiente, por lo que no se necesita ninguna importación adicional.
import '@univerjs/sheets-drawing/facade'import '@univerjs/sheets-drawing-ui/facade'Agregar DOM flotante
El método FWorksheet.addFloatDomToPosition(layer) puede agregar un elemento DOM flotante a una posición específica.
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()// You should register components at an appropriate time (e.g., when Univer is loaded)// This is a React component. For Vue3 components, the third parameter should be `{ framework: 'vue3' }`univerAPI.registerComponent( 'myFloatDom', ({ data }) => ( <div style={{ width: '100%', height: '100%', background: '#fff', border: '1px solid #ccc', boxSizing: 'border-box' }}> popup content: {' '} {data?.label} </div> ),)// Add a floating DOM// If disposable is null, floating DOM addition failedconst disposable = fWorksheet.addFloatDomToPosition({ componentKey: 'myFloatDom', initPosition: { startX: 100, endX: 300, startY: 100, endY: 200, }, // Component data data: { label: 'hahah', },})// 2 秒后移除浮动 DOMsetTimeout(() => { disposable?.dispose()}, 2000)El método FWorksheet.addFloatDomToRange(range, layer, domLayout) puede agregar un elemento DOM flotante a un rango específico.
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()// Register a range loading componentfunction RangeLoading() { const divStyle = { width: '100%', height: '100%', backgroundColor: '#fff', border: '1px solid #ccc', boxSizing: 'border-box' as const, display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center' as const, transformOrigin: 'top left', } return ( <div style={divStyle}> Loading... </div> )}univerAPI.registerComponent('RangeLoading', RangeLoading)// Add the range loading component covering the range A1:C3const fRange = fWorksheet.getRange('A1:C3')const disposable = fWorksheet.addFloatDomToRange(fRange, { componentKey: 'RangeLoading' }, {}, 'myRangeLoading')// Remove the floating DOM after 2 secondssetTimeout(() => { disposable?.dispose()}, 2000)// another example-------------------// Register a float button componentfunction FloatButton() { const divStyle = { width: '100px', height: '30px', backgroundColor: '#fff', border: '1px solid #ccc', boxSizing: 'border-box' as const, display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center' as const, cursor: 'pointer', } const clickHandler = () => { console.warn('click') } return ( <div style={divStyle} onClick={clickHandler}> FloatButton </div> )}univerAPI.registerComponent('FloatButton', FloatButton)// Add the float button to the range A5:C7, position is start from A5 cell, and width is 100px, height is 30px, margin is 100% of range width and heightconst fRange2 = fWorksheet.getRange('A5:C7')const disposable2 = fWorksheet.addFloatDomToRange( fRange2, { componentKey: 'FloatButton', }, { width: 100, height: 30, marginX: '100%', // margin percent to range width, or pixel marginY: '100%', }, 'myFloatButton',)El método FWorksheet.addFloatDomToColumnHeader(column, layer, domPos) puede agregar un elemento DOM flotante a una columna específica encabezado.
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()// Register a float button componentfunction FloatButton() { const divStyle = { width: '100px', height: '30px', backgroundColor: '#fff', border: '1px solid #ccc', boxSizing: 'border-box' as const, display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center' as const, cursor: 'pointer', } const clickHandler = () => { console.warn('click') } return ( <div style={divStyle} onClick={clickHandler}> FloatButton </div> )}univerAPI.registerComponent('FloatButton', FloatButton)// Add the float button to the column D header, position is right align, width is 100px, height is 30px, margin is 0const disposable = fWorksheet.addFloatDomToColumnHeader( 3, { componentKey: 'FloatButton', allowTransform: false, }, { width: 100, height: 30, marginX: 0, marginY: 0, horizonOffsetAlign: 'right', }, 'myFloatButton',)// Remove the float button after 2 secondssetTimeout(() => { disposable?.dispose()}, 2000)Insertar imágenes flotantes
FWorksheet.newOverGridImage() crea un generador de imágenes flotantes, devuelve una instancia de FOverGridImageBuilder y genera un objeto ISheetImage para insertar imágenes flotantes a través de llamadas en cadena.
Aquí hay algunos métodos de miembros en FOverGridImageBuilder:
| Método | Descripción |
|---|---|
| buildAsync | Construya la imagen y devuelva el objeto ISheetImage |
| setSource | Establezca el origen de la imagen |
| setColumn | Establezca la posición horizontal de la imagen |
| setRow | Establezca la posición vertical de la imagen |
| setColumnOffset | Establezca el desplazamiento horizontal de la imagen |
| setRowOffset | Establezca el desplazamiento vertical de la imagen |
| setWidth | Establecer el ancho de la imagen |
| setHeight | Establecer el alto de la imagen |
| setAnchorType | Establezca el tipo de anclaje de la imagen, ya sea que la posición y el tamaño cambien con la celda |
| setCropTop | Establezca la región de recorte de la imagen definiendo los bordes superiores, mostrando así la parte específica de la imagen que desea |
| setCropLeft | Establezca la región de recorte de la imagen definiendo los bordes izquierdos, mostrando así la parte específica de la imagen que desea |
| setCropBottom | Establezca la región de recorte de la imagen definiendo los bordes inferiores, mostrando así la parte específica de la imagen que desea |
| setCropRight | Establezca el recortar la región de la imagen definiendo los bordes derechos, mostrando así la parte específica de la imagen que desea |
| setRotate | Establecer el ángulo de rotación de la imagen |
// create a new image builder and set image source.// then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, width is 500px, height is 300pxconst fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const image = await fWorksheet.newOverGridImage() .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL) .setColumn(5) .setRow(5) .setWidth(500) .setHeight(300) .buildAsync()fWorksheet.insertImages([image])También puede insertar imágenes mediante el método FWorksheet.insertImage(url, column, row, offsetX, offsetY).
// Insert an image to the sheet, position is F6, offset is 10pxconst fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()const result = await fWorksheet.insertImage('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', 5, 5, 10, 10)Obtener imágenes flotantes
El método FWorksheet.getImages() puede obtener todas las imágenes flotantes en la hoja de trabajo y devolver una matriz de FOverGridImage[] instancias.
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()const images = fWorksheet.getImages()images.forEach((image) => { image.getId()})También puede obtener una imagen flotante por su ID usando el método FWorksheet.getImageById(id).
Actualizar imágenes flotantes
El método FWorksheet.updateImages(sheetImages) puede actualizar la posición y el tamaño de las imágenes flotantes. etc.
// create a new image builder and set image source.// then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, width is 500px, height is 300pxconst fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const image = await fWorksheet.newOverGridImage() .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL) .setColumn(5) .setRow(5) .setWidth(500) .setHeight(300) .buildAsync()fWorksheet.insertImages([image])// update the image width to 100px and height to 50px after 4 secondssetTimeout(async () => { const imageBuilder = fWorksheet.getImageById(image.drawingId).toBuilder() const newImage = await imageBuilder.setWidth(100).setHeight(50).buildAsync() fWorksheet.updateImages([newImage])}, 4000)Eliminar imágenes flotantes
El método FWorksheet.deleteImages(sheetImages) puede eliminar imágenes flotantes.
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()const image = fWorksheet.getImages()[0]// Delete the first image of the sheetfWorksheet.deleteImages([image])Insertar imágenes de celdas
El método FRange.insertCellImageAsync(file) puede insertar imágenes de celdas.
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Insert an image into the cell A10const fRange = fWorksheet.getRange('A10')const result = await fRange.insertCellImageAsync('https://avatars.githubusercontent.com/u/61444807?s=48&v=4')Imagen de fondo de la hoja
Una hoja puede mostrar una imagen repetida detrás de las celdas. Se almacena en IWorksheetData.backgroundImage, aparte de imágenes flotantes o de celda. El preset Drawing incluye esta función. En modo plugin necesitas @univerjs/sheets-drawing, su Facade y Drawing UI para renderizado y carga.
import '@univerjs/sheets-drawing/facade'const sheet = univerAPI.getActiveWorkbook()?.getActiveSheet()if (!sheet) throw new Error('No active worksheet')sheet.setBackgroundImage('https://example.com/background.png')console.log(sheet.getBackgroundImage())sheet.deleteBackgroundImage()setBackgroundImage() usa ImageSourceType.URL por defecto y reemplaza el fondo; deleteBackgroundImage() lo elimina. Ambas operaciones admiten deshacer/rehacer. La UI usa el servicio de imágenes configurado. El fondo es decorativo y no se imprime.
Opacidad de las imágenes
Las imágenes flotantes admiten opacidad global. setOpacity() acepta un número finito entre 0 (transparente) y 1 (opaco), con 1 como valor predeterminado; los valores inválidos provocan RangeError. Puede configurarse en FOverGridImageBuilder antes de crear la imagen o en un FOverGridImage existente. Ambos exponen getOpacity(). El panel de propiedades también permite ajustar la transparencia.
const sheet = univerAPI.getActiveWorkbook()?.getActiveSheet()const image = sheet?.getImages()[0]if (image) { image.setOpacity(0.5) console.log(image.getOpacity())}Tamaño y anclaje de imágenes
Las imágenes insertadas con el selector integrado conservan la proporción y se reducen si hace falta para caber en 500 × 500 píxeles, sin ampliar imágenes pequeñas. El tamaño visible es distinto del límite de bytes allowImageSize. Con el Facade puedes indicar las dimensiones.
SheetDrawingAnchorType.Position se mueve con las celdas sin cambiar de tamaño, Both sigue posición y tamaño del rango, y None fija ambos. Ocultar y mostrar filas o columnas conserva los anclajes: las imágenes ligadas al tamaño del rango pueden reducirse temporalmente y recuperarse al mostrarlo. No sobrescribas los anclajes con esa geometría temporal.
¿Cómo es esta guía?