形状
形状用于在文档中插入和编辑图形,涵盖基本几何形状、箭头和流程图元素。
介绍
在 Univer Docs 中,形状支持以下操作:
- 添加矩形、圆形、箭头等几何形状;
- 调整填充颜色、边框和文字;
- 将形状放置在文档中的任意位置。
插件模式
安装
pnpm add @univerjs-pro/engine-formula @univerjs-pro/docs-shape @univerjs-pro/docs-shape-uinpm install @univerjs-pro/engine-formula @univerjs-pro/docs-shape @univerjs-pro/docs-shape-uiyarn add @univerjs-pro/engine-formula @univerjs-pro/docs-shape @univerjs-pro/docs-shape-uibun add @univerjs-pro/engine-formula @univerjs-pro/docs-shape @univerjs-pro/docs-shape-ui形状还依赖 @univerjs-pro/engine-formula 中的 UniverProFormulaEnginePlugin。基础初始化代码中原有的 UniverFormulaEnginePlugin 导入和注册需要替换为该插件。同时注册两种公式引擎时,插入形状可能报依赖未注册的错误。
使用
import { UniverDocsShapePlugin } from '@univerjs-pro/docs-shape'import { UniverDocsShapeUIPlugin } from '@univerjs-pro/docs-shape-ui'import DocsShapeUIZhCN from '@univerjs-pro/docs-shape-ui/locale/zh-CN'import { UniverProFormulaEnginePlugin } from '@univerjs-pro/engine-formula'import { LocaleType, mergeLocales, Univer } from '@univerjs/core'import '@univerjs-pro/docs-shape-ui/lib/index.css'const univer = new Univer({ locale: LocaleType.ZH_CN, locales: { [LocaleType.ZH_CN]: mergeLocales( DocsShapeUIZhCN, ), },})univer.registerPlugin(UniverProFormulaEnginePlugin)univer.registerPlugin(UniverDocsShapePlugin)univer.registerPlugin(UniverDocsShapeUIPlugin)使用 Univer 商业许可证时,配置方式参见在客户端使用许可证。
移动端适配
请先完成移动端编辑器的配置。在本页插件模式的初始化代码中,将下表中的桌面端注册替换为同一个包导出的移动端插件,并且必须在打开文档前完成替换。模型插件、样式、语言包和 Facade 导入均需保留,两个版本不要同时注册。
| 来源包 | 桌面端注册 | 移动端注册 |
|---|---|---|
@univerjs-pro/docs-shape-ui | UniverDocsShapeUIPlugin | UniverDocsShapeMobileUIPlugin |
编辑形状文字
使用下面示例或前面示例中 insertShape() 返回的形状对象。getText() 返回实时的 FShapeText 句柄。用 getPlainText() 读取纯文本,用 setText() 替换全部文字,再通过字体、颜色和对齐相关的方法设置格式。
import '@univerjs-pro/docs-shape/facade'const document = univerAPI.getActiveDocument()const paragraph = document?.getParagraphs()[0]if (!document || !paragraph) throw new Error('No active document paragraph')const shape = document.insertShape({ shapeType: univerAPI.Enum.ShapeTypeEnum.Rect, placement: { wrappingStyle: univerAPI.Enum.TextWrappingStyle.INLINE, anchor: { paragraphId: paragraph.getId(), segmentId: paragraph.getSegmentId() }, },})if (!shape) throw new Error('Shape is not available')const shapeText = shape.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() 替换已有文字;一个形状需要多种文字样式时,使用 setRichText()。修改现有富文本时,先调用 getRichText()?.copy(),修改构建器后再传给 setRichText();仅修改这个脱离出来的构建器不会自动写回。更多选项参见文字样式和文本框内边距与布局。
const richText = univerAPI.newRichText() .text('Quarterly ') .bold('review')shapeText.setRichText(richText)形状格式刷
先选中源形状,启用格式刷,再选中目标形状。格式刷会复制填充、描边、效果和受支持的文字格式,目标形状的标识、几何信息、文字内容和公式绑定保持原样。清除格式会恢复插入时的默认样式。SmartArt 不参与。形状 UI 插件会自动注册这一行为。
你觉得这篇文档如何?