本文原创发布在华为开发者社区,更多鸿蒙场景化示例请见华为开发者联盟官网“行业实践与常见问题”专题页。

介绍

本示例基于 RichEditor 组件实现多种富文本编辑功能,主要包括文本颜色、加粗、斜体、下划线、删除线、阴影,段落对齐等编辑功能。

多种富文本编辑功能源码链接

效果预览

图片名称

实现思路

  1. 通过 onSelectionChange 事件回调来获取当前选中的选区位置,并更新工具栏状态显示。
    RichEditor({ controller: this.controller })
    .onSelectionChange((range) => {
        // 光标移动时,更新编辑栏状态显示
        // 获取选区内文本样式
        let textStyleResult = RichEditorUtil.getFirstTextSpanStyle(this.controller, range);
        
        // ...获取文本样式信息并记录

        // 更新当前样式信息
        this.currentStyle = {
        fontColor: COLOR_LIST[this.currentColor],
        fontWeight: this.currentBold ? FontWeight.Bold : FontWeight.Normal,
        decoration: { type: this.currentDecoration },
        fontStyle: this.currentItalics ? FontStyle.Italic : FontStyle.Normal,
        textShadow: this.currentShadow ? {
            radius: 2,
            offsetY: vp2px(1),
            offsetX: vp2px(1),
            type: ShadowType.BLUR
        } : { radius: 0 }
        };
        // 光标变动后,应设置为跟随周围样式
        this.controller.setTypingStyle(this.currentStyle);
    });
  1. 通过 getSpans 方法获取选区内样式,当仅有光标无选区时,需要特殊判断。
    static getFirstTextSpanStyle(controller: RichEditorController, range: RichEditorRange): RichEditorTextSpanResult | undefined {
    let start = range.start ?? 0;
    let end = range.end ?? -1;
    if (start === end) { // 单独光标,无选区,走搜索匹配
        let spans = controller.getSpans({ start: start - 1, end: range.end });
        for (let i = 0; i < spans.length; i++) {
        let span = spans[i] as RichEditorTextSpanResult;
        if (span.textStyle !== undefined) {
            return span;
        }
        }
    } else {
        // 有选区时,默认选区范围
        let spans = controller.getSpans(range);
        if (spans) {
        for (let i = 0; i < spans.length; i++) {
            let span = spans[i] as RichEditorTextSpanResult;
            if (span.textStyle !== undefined) {
            return span;
            }
        }
        }
    }
    // 无匹配
    return undefined;
    }
  1. 通过 RichEditorController 的 setTypingStyle 方法来设置输入时的文本样式;通过 updateSpanStyle 方法来设置选中区域的文本样式。
    static updateSpanStyle(controller: RichEditorController, range: RichEditorSelection, style: RichEditorUpdateTextSpanStyleOptions) {
    let start = range.selection[0];
    let end = range.selection[1];
    if (start === end) {
        // 无选区,仅光标,更新输入样式
        controller.setTypingStyle(style.textStyle);
    } else {
        controller.updateSpanStyle(style);
    }
    }
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐