HarmonyOS鸿蒙Next中RichEditor删除ImageSpan图片,如何获取对应图片的信息
HarmonyOS鸿蒙Next中RichEditor删除ImageSpan图片,如何获取对应图片的信息 在RichEditor组件中添加了个ImageSpan,图片是这个$r(‘app.media.xxx’),用户编辑后,我从this.controller.getSpans()获取richeditor的所有span,怎么知道某个ImageSpan对应的哪个图片?
可以将图片资源放到rawfile文件夹下,再通过getSpan获取valueResourceStr字段,能够正常获取到图片的名称
@Entry
@Component
struct richEditorPage {
controller: RichEditorController = new RichEditorController();
options: RichEditorOptions = { controller: this.controller };
build() {
Column() {
RichEditor(this.options)
.onReady(() => {
this.controller.addTextSpan('点击按钮在此处添加image。', {
style: {
fontColor: Color.Black,
fontSize: 15
}
})
})
.width('100%')
.height(100)
Row(){
Button('添加图片', {
buttonStyle: ButtonStyleMode.NORMAL
})
.height(30)
.fontSize(13)
.onClick(() => {
this.controller.addImageSpan($rawfile("image/haoke.webp"), {
imageStyle: {
size: ["57px", "57px"]
}
})
})
Button('获取图片span', {
buttonStyle: ButtonStyleMode.NORMAL
})
.onClick(()=>{
let myList : Array<RichEditorTextSpanResult | RichEditorImageSpanResult>= this.controller.getSpans({start:0})
let imageList = myList.filter((item,index)=>{
if((item as RichEditorImageSpanResult).valueResourceStr){
return true
}else{
return false
}
})
console.info("图片信息:", JSON.stringify(imageList))
})
}
.justifyContent(FlexAlign.SpaceAround)
.width('100%')
}
.border({width:1})
}
}
更多关于HarmonyOS鸿蒙Next中RichEditor删除ImageSpan图片,如何获取对应图片的信息的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,删除RichEditor
中的ImageSpan
图片时,可以通过ImageSpan
的getDrawable()
方法获取图片的Drawable
对象,进而通过Drawable
的getBounds()
方法获取图片的尺寸信息。若需要获取图片的路径或资源ID,需在创建ImageSpan
时自行保存相关信息。删除操作可通过SpannableStringBuilder
的removeSpan()
方法实现。
在HarmonyOS Next中,要获取RichEditor中ImageSpan对应的图片信息,可以通过以下方式实现:
- 当创建ImageSpan时,建议为每个图片设置唯一的tag标识:
const imageSpan = new ImageSpan(context, $r('app.media.xxx'));
imageSpan.setTag("image_"+uniqueId); // 设置唯一标识
- 获取所有span后,可以通过判断span类型和获取tag来识别图片:
const spans = this.controller.getSpans();
spans.forEach(span => {
if(span instanceof ImageSpan) {
const imageTag = span.getTag(); // 获取设置的标识
// 根据tag匹配具体图片资源
}
});
- 也可以直接获取ImageSpan的图片资源:
const imageDrawable = span.getDrawable();
// 通过drawable信息判断具体图片
注意:如果图片是通过资源ID($r)添加的,建议在创建ImageSpan时维护一个资源ID与span的映射关系,方便后续查询。