Read the original article:RichEditor Obtains Image Information From ImageSpan
RichEditor Obtains Image Information From ImageSpan
Requirement Description
When adding an ImageSpan to the RichEditor component using $r('app.media.background') and retrieving span information through getSpans, the image name obtained is inconsistent with the actual image name.
This happens because resource files in the base directory are compiled into binary files and assigned resource IDs.
Example image:
Background Knowledge
RichEditor is a component that supports mixed text and image layout and interactive text editing. You can obtain all span information using the getSpans method.
Implementation Steps
Place the image resources in the rawfile folder. Then, by using getSpans to retrieve the valueResourceStr field, the image name can be obtained correctly.
Code Snippet
@Entry
@Component
struct RichEditorPage {
controller: RichEditorController = new RichEditorController();
options: RichEditorOptions = { controller: this.controller };
build() {
Column() {
RichEditor(this.options)
.onReady(() => {
this.controller.addTextSpan('Click the button to add an image here', {
style: {
fontColor: Color.Black,
fontSize: 15
}
});
})
.width('100%')
.height(100);
Row() {
Button('Add image', {
buttonStyle: ButtonStyleMode.NORMAL
})
.height(30)
.fontSize(13)
.onClick(() => {
this.controller.addImageSpan($rawfile('background.png'), {
imageStyle: {
size: ['57px', '57px']
}
});
});
Button('Get the image span', {
buttonStyle: ButtonStyleMode.NORMAL
})
.onClick(() => {
this.controller.getSpans({ start: 0 }).forEach(item => {
console.info(`imageName is : ${(item as RichEditorImageSpanResult).valueResourceStr}`);
});
});
}
.justifyContent(FlexAlign.SpaceAround)
.width('100%');
}
.border({ width: 1 });
}
}
Test Results
Restrictions and Limitations
This example supports API Version 20 Release and later versions.
This example supports HarmonyOS 6.0.0 Release SDK and later versions.
This example requires DevEco Studio 6.0.0 Release or later for building and running.


Top comments (0)