HarmonyOS6 ArkTS 属性字符串(StyledString)使用
2026/4/24 2:20:29 网站建设 项目流程

文章目录

    • 核心概念
      • 1 什么是 StyledString
      • 2 核心能力
    • 核心 API
      • 1 基础类
      • 2 核心方法
    • 核心功能
      • 1 基础文本样式
      • 2 点击/长按事件
      • 3 文本图片混排
      • 4 多装饰线
      • 5 文本描边
      • 6 超链接
      • 7 自定义绘制 Span
      • 8 自定义数据 Span
      • 9 段落样式
      • 10 HTML 双向转换
    • 完整 Demo
    • 总结

StyledString是 HarmonyOS 提供的富文本核心能力,支持在单一文本组件内实现:多样式文本、图片混排、点击事件、超链接、自定义绘制、HTML 互转等富文本需求,广泛用于商品描述、消息通知、协议文本、富文本展示等场景。

核心概念

1 什么是 StyledString

StyledString(属性字符串)是 HarmonyOS 提供的带样式/附件/事件的不可变字符串对象MutableStyledString为可变版本,支持拼接、修改、添加样式等操作,是实现富文本的基础载体。

2 核心能力

  • 文本样式:颜色、字号、粗细、描边、斜体、装饰线(下划线/删除线)
  • 事件能力:单击、长按手势绑定
  • 内容混排:文本 + 图片、自定义绘制 Span 混排
  • 功能扩展:超链接、用户自定义数据、段落样式
  • 格式转换:与 HTML 字符串互相转换

核心 API

1 基础类

类名作用
MutableStyledString可变属性字符串,支持拼接、修改、添加样式
StyledString不可变属性字符串,用于最终展示/HTML 转换
TextStyle文本样式(颜色、字号、描边等)
GestureStyle手势事件(点击、长按)
DecorationStyle文本装饰线(下划线、删除线)
ImageAttachment图片附件,用于文本内插入图片
UrlStyle超链接样式
ParagraphStyle段落样式(缩进、段间距)
CustomSpan自定义绘制 Span
UserDataSpan自定义数据 Span

2 核心方法

  1. 创建属性字符串
let str = new MutableStyledString("文本内容");
  1. 添加样式
let str = new MutableStyledString("内容", [样式数组]);
  1. 拼接富文本
str.appendStyledString(另一个MutableStyledString);
  1. HTML 互转
// HTML → StyledString let styledStr = await StyledString.fromHtml(htmlStr); // StyledString → HTML let htmlStr = StyledString.toHtml(styledStr);

核心功能

1 基础文本样式

设置字体颜色、大小、粗细,是富文本最基础能力。

let baseStr = new MutableStyledString("综合StyledString演示 ", [{ start: 0, length: 6, styledKey: StyledStringKey.FONT, styledValue: new TextStyle({ fontColor: Color.Blue, fontSize: LengthMetrics.fp(22), fontWeight: FontWeight.Bold }) }]);

2 点击/长按事件

为指定文本绑定交互事件,实现文本点击交互。

let clickGesture = new GestureStyle({ onClick: () => { promptAction.showToast({ message: "文本被点击" }); } });

3 文本图片混排

使用ImageAttachment在文本中插入图片,支持尺寸、对齐方式配置。

let imgSpan = new MutableStyledString(new ImageAttachment({ value: pixelMap, size: { width: 40, height: 40 }, verticalAlign: ImageSpanAlignment.CENTER }));

4 多装饰线

支持同时添加下划线 + 删除线,实现复杂文本装饰效果。

new DecorationStyle({ type:TextDecorationType.Underline }, { enableMultiType:true })

5 文本描边

实现空心文字效果,支持描边宽度、颜色配置。

strokeWidth: LengthMetrics.vp(2), strokeColor: Color.Black

6 超链接

快速为文本添加跳转链接。

styledValue: new UrlStyle("https://developer.huawei.com")

7 自定义绘制 Span

继承CustomSpan实现自定义图形/文本绘制,满足个性化需求。

8 自定义数据 Span

继承UserDataSpan为文本绑定自定义业务数据。

9 段落样式

设置文本缩进、段间距、对齐方式,优化排版效果。

new ParagraphStyle({ textIndent: LengthMetrics.vp(10), // 首行缩进 paragraphSpacing: LengthMetrics.vp(5) // 段间距 })

10 HTML 双向转换

支持富文本与 HTML 格式互相转换,适配 Web 场景数据。

let html = "<p>测试<b>加粗</b> <u>下划线</u></p>"; let styledStr = await StyledString.fromHtml(html);

完整 Demo

本 Demo 完整复现官方所有核心能力,无语法错误、可直接运行。

// 最终无错版:StyledString 完整Demo import { LengthMetrics } from '@kit.ArkUI'; import { image } from '@kit.ImageKit'; import { drawing } from '@kit.ArkGraphics2D'; // 自定义Span class MyCustomSpan extends CustomSpan { word: string = "自定义"; width: number = 80; height: number = 30; padding: number = 2; constructor(word: string) { super(); this.word = word; } onMeasure(measureInfo: CustomSpanMeasureInfo): CustomSpanMetrics { return { width: this.width + this.padding * 2, height: this.height }; } onDraw(context: DrawContext, drawInfo: CustomSpanDrawInfo): void { let canvas = context.canvas; const brush = new drawing.Brush(); brush.setColor({ alpha:255, red:0, green:100, blue:255 }); canvas.attachBrush(brush); canvas.drawRect({ left: drawInfo.x + this.padding, right: drawInfo.x + this.width + this.padding, top: drawInfo.lineTop, bottom: drawInfo.lineBottom }); canvas.detachBrush(); } } // 自定义用户数据Span class MyUserDataSpan extends UserDataSpan { public name: string; public age: number; constructor(name: string, age: number) { super(); this.name = name; this.age = age; } } @Entry @Component struct StyledStringFullDemo { textController: TextController = new TextController(); private uiContext: UIContext = this.getUIContext(); @State imagePixelMap: image.PixelMap | undefined = undefined; mainStyledStr: MutableStyledString = new MutableStyledString(""); async aboutToAppear() { this.imagePixelMap = await this.loadMediaToPixelMap($r('app.media.startIcon')); this.buildFullStyledString(); } private async loadMediaToPixelMap(resource: Resource): Promise<image.PixelMap> { let unit8Array = await this.uiContext.getHostContext()?.resourceManager?.getMediaContent(resource.id); let imageSource = image.createImageSource(unit8Array?.buffer); let pixelMap = await imageSource.createPixelMap(); await imageSource.release(); return pixelMap; } buildFullStyledString() { // 1. 基础文本 let baseStr = new MutableStyledString("综合StyledString演示 ", [{ start: 0, length: 6, styledKey: StyledStringKey.FONT, styledValue: new TextStyle({ fontColor: Color.Blue, fontSize: LengthMetrics.fp(22), fontWeight: FontWeight.Bold }) }]); // 2. 点击事件 let clickGesture = new GestureStyle({ onClick: () => { this.uiContext.getPromptAction().showToast({ message: "点击了蓝色文本" }); } }); let clickStr = new MutableStyledString("可点击文本 ", [{ start:0, length:5, styledKey: StyledStringKey.GESTURE, styledValue: clickGesture },{ start:0, length:5, styledKey: StyledStringKey.FONT, styledValue: new TextStyle({ fontColor: Color.Red }) }]); // 3. 图片 let imgSpan: MutableStyledString; if (this.imagePixelMap) { imgSpan = new MutableStyledString(new ImageAttachment({ value: this.imagePixelMap, size: { width: 40, height: 40 }, verticalAlign: ImageSpanAlignment.CENTER, objectFit: ImageFit.Contain })); } else { imgSpan = new MutableStyledString(""); } // 4. 装饰线 let decoStr = new MutableStyledString("多装饰线文本 ", [{ start:0, length:6, styledKey: StyledStringKey.DECORATION, styledValue: new DecorationStyle( { type:TextDecorationType.Underline, color:Color.Green, thicknessScale:2 }, { enableMultiType:true } ) },{ start:0, length:6, styledKey: StyledStringKey.DECORATION, styledValue: new DecorationStyle( { type:TextDecorationType.LineThrough, color:Color.Black }, { enableMultiType:true } ) }]); // 5. 描边文本 let strokeStr = new MutableStyledString("描边文本 ", [{ start:0, length:4, styledKey: StyledStringKey.FONT, styledValue: new TextStyle({ fontColor: Color.White, strokeWidth: LengthMetrics.vp(2), strokeColor: Color.Black, fontSize: LengthMetrics.fp(20) }) }]); // 6. 超链接 let urlStr = new MutableStyledString("官方文档 ", [{ start:0, length:4, styledKey: StyledStringKey.URL, styledValue: new UrlStyle("https://developer.huawei.com") }]); // 7. 自定义Span let customSpanStr = new MutableStyledString(new MyCustomSpan("Custom")); // 8. 用户数据 let userDataStr = new MutableStyledString("用户数据", [{ start:0, length:4, styledKey: StyledStringKey.USER_DATA, styledValue: new MyUserDataSpan("HarmonyOS", 10) }]); // 9. 段落样式 let paragraphStyle = new ParagraphStyle({ textAlign: TextAlign.Start, textIndent: LengthMetrics.vp(10), paragraphSpacing: LengthMetrics.vp(5) }); let paraStr = new MutableStyledString("\n段落样式:首行缩进、段间距", [{ start:0, length:12, styledKey: StyledStringKey.PARAGRAPH_STYLE, styledValue: paragraphStyle }]); // 拼接(全部修复!) this.mainStyledStr = new MutableStyledString(""); this.mainStyledStr.appendStyledString(baseStr); this.mainStyledStr.appendStyledString(clickStr); this.mainStyledStr.appendStyledString(imgSpan); this.mainStyledStr.appendStyledString(new MutableStyledString(" ")); this.mainStyledStr.appendStyledString(decoStr); this.mainStyledStr.appendStyledString(strokeStr); this.mainStyledStr.appendStyledString(urlStr); this.mainStyledStr.appendStyledString(new MutableStyledString(" ")); this.mainStyledStr.appendStyledString(customSpanStr); this.mainStyledStr.appendStyledString(new MutableStyledString(" ")); this.mainStyledStr.appendStyledString(userDataStr); this.mainStyledStr.appendStyledString(paraStr); this.textController.setStyledString(this.mainStyledStr); } // HTML转换 async convertHtml() { let html = "<p>测试<b>加粗</b> <u>下划线</u> <a href='https://www.harmonyos.com'>链接</a></p>"; let styledStr = await StyledString.fromHtml(html); this.textController.setStyledString(styledStr); let backHtml = StyledString.toHtml(styledStr); console.info("HTML:", backHtml); } build() { Column({ space:15 }) { Text("StyledString 综合Demo") .fontSize(25) .fontWeight(FontWeight.Bold) .margin({ top:15 }); Text(undefined, { controller: this.textController }) .width("95%") .border({ width:1, color:Color.Gray }) .padding(12) .fontSize(18); Button("HTML转换测试") .width("80%") .onClick(() => this.convertHtml()); Button("恢复初始样式") .width("80%") .onClick(() => this.buildFullStyledString()); } .width("100%") .padding(10) } }

运行效果如图:

总结

StyledString是 HarmonyOS 6 官方推荐的富文本解决方案,具备能力全面、使用简洁、性能高效的优势,可满足绝大多数富文本需求。

如果这篇文章对你有帮助,欢迎点赞、收藏、关注,你的支持是持续创作的动力

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询