Arkts解决方案<文本样式处理>
富文本处理
·
在项目中我们经常会遇到同一段文本特定文字样式特殊处理的情况,如:这是一段特殊文字,这句话中对‘特殊’两个进行加粗、字体大小、改变颜色等进行突出显示。这个时候就用到属性字符串(StyledString/MutableStyledString),MutableStyledString继承自StyledString,使用方式为通过TextController提供的setStyledString方法,将属性字符串附加到文本组件,并推荐在onPageShow或者文本组件的onAppear回调中触发绑定。
需要注意的是在aboutToAppear中调用setStyledString方法时,由于该方法运行阶段组件尚未完成创建并成功挂载节点树,因此无法在页面初始化时显示属性字符串。
1、基础使用案例:
import { LengthMetrics } from "@kit.ArkUI";
export function MutableStyledStringPageBuilder() {
MutableStyledStringPage()
}
export struct MutableStyledStringPage{
pageInfos: NavPathStack = new NavPathStack();
private content:string = '这是测试一和测试二。';
controller: TextController = new TextController(); // 文本控制器
textStyleAttrs: TextStyle =
new TextStyle({
fontWeight: FontWeight.Bold, // 字体粗细
fontSize: LengthMetrics.vp(16), // 字体大小
fontStyle: FontStyle.Normal, // 字体样式
fontColor:Color.Black // 字体颜色
});
textStyleAttrs2: TextStyle =
new TextStyle({
fontWeight: FontWeight.Bold,
fontSize: LengthMetrics.vp(16),
fontStyle: FontStyle.Normal,
fontColor:Color.Red
});
build() {
NavDestination() {
Column() {
Text(undefined, { controller: this.controller }); // 使用controller对文字进行设置
}.width('100%')
}.onReady((context: NavDestinationContext) => {
this.pageInfos = context.pathStack
// 推荐在onReady中使用,但是不能使用条件渲染
this.initStyledString();
})
}
initStyledString() {
// 不需要对文本渲染后进行改变使用StyledString,反着使用MutableStyledString
const mutableStr = new MutableStyledString(this.content,[
{
start:2, // 开始位置
length:3, // 改变文字长度
styledKey: StyledStringKey.FONT, // 文本类型
styledValue: this.textStyleAttrs // 使用样式1
},
{
start:6,
length:3,
styledKey: StyledStringKey.FONT,
styledValue: this.textStyleAttrs2 // 使用样式2
}
]);
this.controller.setStyledString(mutableStr); // 设置样式
}
}

2、应用文本阴影案例
textStyleAttrs3: TextShadowStyle = new TextShadowStyle({
radius: 5,
type: ShadowType.COLOR,
color: Color.Red,
offsetX: 10,
offsetY: 10
})

3、设置事件案例
// 事件设置
gestureStyleAttr: GestureStyle = new GestureStyle({
onClick: () => {
this.backgroundColor1 = Color.Green;
},
onLongPress: () => {
this.backgroundColor1 = Color.Grey;
}
});
// 样式设置
const mutableStr = new MutableStyledString(this.content, [
{
start: 0, // 事件起始位
length: 1, // 长度
styledKey: StyledStringKey.GESTURE,
styledValue: this.gestureStyleAttr
}
最后效果为,点击第一个文字改变背景颜色为绿色,长按第一个文字背景颜色改变为灰色。
日常开发中最常用的就是以上三种。
更多推荐



所有评论(0)