使用Text组件的StyledString/MutableStyledString实现图文混排富文本展示功能,预计实现URL链接点击跳转能力,图片点击放大能力,以及文本样式展示能力,但在实现过程中发现,当设置StyledString/MutableStyledString的value值ImageAttachment或CustomSpan时,style参数不生效。
属性字符串(StyledString/MutableStyledString)的constructor()构造函数,当value的类型为ImageAttachment或CustomSpan时,style参数不生效。需要设置style时,通过setStyle等方法实现。
通过setStyle()方法来设置style并绑定点击事件。
@Entry
@Component
struct StyledStringExample {
controller: TextController = new TextController();
image: ImageAttachment = new ImageAttachment({
resourceValue: $r('app.media.startIcon'),
size: { width: 50, height: 50 },
});
spanStyle: SpanStyle = {
start: 0,
length: 1,
styledKey: StyledStringKey.GESTURE,
styledValue: new GestureStyle({
onClick: () => {
console.info('clickGestureAttr object trigger click event');
}
})
};
arrayList: Array<StyleOptions> = [this.spanStyle];
mutableStyledString: MutableStyledString = new MutableStyledString(this.image);
onPageShow(): void {
// 通过setStyle方法,给图片添加样式
this.mutableStyledString.setStyle(this.spanStyle);
this.controller.setStyledString(this.mutableStyledString);
}
build() {
Column() {
// 点击图片出现弹窗
Text(undefined, { controller: this.controller })
.borderWidth(1)
}.padding(50)
}
}