• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 属性字符串 (系统接口)
2
3方便灵活应用文本样式的对象,可通过TextController中的[setStyledString](./ts-basic-components-text.md#setstyledstring12)方法与Text组件绑定,可通过RichEditorStyledStringController中的[setStyledString](ts-basic-components-richeditor.md#setstyledstring12)方法与RichEditor组件绑定。
4
5>  **说明:**
6>
7>  该组件从API version 13开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
8>
9>  当前页面仅包含本模块的系统接口,其他公开接口参见[属性字符串](ts-universal-styled-string.md)。
10
11## StyledString
12
13### marshalling
14
15static marshalling(styledString: StyledString): ArrayBuffer
16
17序列化属性字符串。
18
19**系统接口:** 此接口为系统接口。
20
21**系统能力:** SystemCapability.ArkUI.ArkUI.Full
22
23**参数:**
24
25| 参数名 | 类型 | 必填 | 说明 |
26| ----- | ----- | ---- | ---- |
27| styledString | [StyledString](ts-universal-styled-string.md) | 是  | 属性字符串参数。 |
28
29**返回值:**
30
31| 类型              |说明       |
32| ------- | --------------------------------- |
33| ArrayBuffer | 序列化后的buffer信息。<br/>**说明:** <br/>目前支持文本和图片。 |
34
35### marshalling<sup>19+</sup>
36
37static marshalling(styledString: StyledString, callback: StyledStringMarshallCallback): ArrayBuffer
38
39序列化属性字符串,通过定义回调来序列化属性字符串的[StyledStringMarshallingValue](#styledstringmarshallingvalue19)。
40
41**系统接口:** 此接口为系统接口。
42
43**系统能力:** SystemCapability.ArkUI.ArkUI.Full
44
45**参数:**
46
47| 参数名 | 类型 | 必填 | 说明 |
48| ----- | ----- | ---- | ---- |
49| styledString | [StyledString](ts-universal-styled-string.md) | 是  | 属性字符串参数。 |
50| callback | [StyledStringMarshallCallback](#styledstringmarshallcallback19) | 是 | 如何序列化[StyledStringMarshallingValue](#styledstringmarshallingvalue19)的回调。 |
51
52**返回值:**
53
54| 类型              |说明       |
55| ------- | --------------------------------- |
56| ArrayBuffer | 序列化后的buffer信息。<br/>**说明:** <br/>目前支持文本和图片。 |
57
58### unmarshalling
59
60static unmarshalling(buffer: ArrayBuffer): Promise\<StyledString>
61
62反序列化后得到属性字符串。
63
64**系统接口:** 此接口为系统接口。
65
66**系统能力:** SystemCapability.ArkUI.ArkUI.Full
67
68**参数:**
69
70| 参数名 | 类型 | 必填 | 说明 |
71| ----- | ----- | ---- | ---- |
72| buffer | ArrayBuffer | 是  | 属性字符串序列化后的数据。 |
73
74**返回值:**
75
76| 类型                             | 说明                  |
77| -------------------------------- | --------------------- |
78| Promise\<[StyledString](ts-universal-styled-string.md)> |Promise对象,返回属性字符串。 |
79
80**错误码**:
81
82以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)和[属性字符串错误码](../errorcode-styled-string.md)。
83
84| 错误码ID | 错误信息 |
85| ------- | -------- |
86| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
87| 170002 | Styled string decode error. |
88
89### unmarshalling<sup>19+</sup>
90
91static unmarshalling(buffer: ArrayBuffer, callback: StyledStringUnmarshallCallback): Promise\<StyledString>
92
93反序列化后得到属性字符串,通过定义回调来反序列化[StyledStringMarshallingValue](#styledstringmarshallingvalue19)。
94
95**系统接口:** 此接口为系统接口。
96
97**系统能力:** SystemCapability.ArkUI.ArkUI.Full
98
99**参数:**
100
101| 参数名 | 类型 | 必填 | 说明 |
102| ----- | ----- | ---- | ---- |
103| buffer | ArrayBuffer | 是  | 属性字符串序列化后的数据。 |
104| callback | [StyledStringUnmarshallCallback](#styledstringunmarshallcallback19) | 是 | 如何反序列化ArrayBuffer的回调。 |
105
106**返回值:**
107
108| 类型                             | 说明                  |
109| -------------------------------- | --------------------- |
110| Promise\<[StyledString](ts-universal-styled-string.md)> |Promise对象,返回属性字符串。 |
111
112**错误码**:
113
114以下错误码详细介绍请参考[通用错误码](../../errorcode-universal.md)和[属性字符串错误码](../errorcode-styled-string.md)。
115
116| 错误码ID | 错误信息 |
117| ------- | -------- |
118| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
119| 170002 | Styled string decode error. |
120
121## StyledStringMarshallingValue<sup>19+</sup>
122
123type StyledStringMarshallingValue = UserDataSpan
124
125属性字符串自定义序列化对象类型,需要开发者定义序列化和反序列化的方式。
126
127**系统接口:** 此接口为系统接口。
128
129**系统能力:** SystemCapability.ArkUI.ArkUI.Full
130
131| 类型  | 说明   |
132| ------ | ---------- |
133| [UserDataSpan](ts-universal-styled-string.md#userdataspan) | UserDataSpan样式。 |
134
135## StyledStringMarshallCallback<sup>19+</sup>
136
137type StyledStringMarshallCallback = (marshallableVal: StyledStringMarshallingValue) => ArrayBuffer
138
139属性字符串[StyledStringMarshallingValue](#styledstringmarshallingvalue19)序列化回调类型。
140
141**系统接口:** 此接口为系统接口。
142
143**系统能力:** SystemCapability.ArkUI.ArkUI.Full
144
145**参数:**
146
147| 参数名  | 类型   | 必填 | 说明                          |
148| ------- | ------ | ---- | --------------------------- |
149| marshallableVal | [StyledStringMarshallingValue](#styledstringmarshallingvalue19)| 是 | 属性字符串序列化对象。 |
150
151**返回值:**
152
153| 类型                             | 说明                  |
154| -------------------------------- | --------------------- |
155| ArrayBuffer | [StyledStringMarshallingValue](#styledstringmarshallingvalue19)序列化后的数据。|
156
157## StyledStringUnmarshallCallback<sup>19+</sup>
158
159type StyledStringUnmarshallCallback = (buf: ArrayBuffer) => StyledStringMarshallingValue
160
161属性字符串反序列化ArrayBuffer得到[StyledStringMarshallingValue](#styledstringmarshallingvalue19)回调类型。
162
163**系统接口:** 此接口为系统接口。
164
165**系统能力:** SystemCapability.ArkUI.ArkUI.Full
166
167**参数:**
168
169| 参数名  | 类型   | 必填 | 说明                          |
170| ------- | ------ | ---- | --------------------------- |
171| buf | ArrayBuffer | 是 | [StyledStringMarshallingValue](#styledstringmarshallingvalue19)序列化后的数据。 |
172
173**返回值:**
174
175| 类型                             | 说明                  |
176| -------------------------------- | --------------------- |
177| [StyledStringMarshallingValue](#styledstringmarshallingvalue19) | 反序列化得到的[StyledStringMarshallingValue](#styledstringmarshallingvalue19) 。|
178
179## 示例
180
181### 示例1 (属性字符串序列化和反序列化)
182
183该示例通过marshalling、unmarshalling属性实现了属性字符串序列化和反序列化的功能。
184
185```ts
186// xxx.ets
187import { LengthMetrics } from '@kit.ArkUI';
188
189@Entry
190@Component
191struct Index {
192  @State textTitle: string = "序列化和反序列化接口";
193  @State textResult: string = "Hello world";
194  @State serializeStr: string = "序列化";
195  @State flag: boolean = false;
196  private textAreaController: TextAreaController = new TextAreaController();
197  private buff: Uint8Array = new Uint8Array();
198  fontStyle: TextStyle = new TextStyle({
199    fontWeight: FontWeight.Lighter,
200    fontFamily: 'HarmonyOS Sans',
201    fontColor: Color.Green,
202    fontSize: LengthMetrics.vp(30),
203    fontStyle: FontStyle.Normal
204  });
205  // 创建属性字符串对象
206  styledString: StyledString = new StyledString("Hello world",
207    [{
208      start: 0,
209      length: 11,
210      styledKey: StyledStringKey.FONT,
211      styledValue: this.fontStyle
212    }]);
213
214  @Builder
215  controllableBuild() {
216    Column() {
217      TextArea({
218        text: this.textResult,
219        controller: this.textAreaController
220      }).width('95%').height('40%').enableKeyboardOnFocus(false)
221
222      Button(this.serializeStr)
223        .margin(5)
224        .onClick(async () => {
225          this.flag = !this.flag;
226          if (!this.flag) {
227            console.info("Debug: 反序列化");
228            let styles: StyledString = await StyledString.unmarshalling(this.buff.buffer);
229            this.textTitle = "调取decodeTlv接口后,反序列化的结果显示:";
230            if (styles == undefined) {
231              console.error("Debug: styledString 获取失败!!!");
232              return;
233            }
234            this.textResult = styles.getString();
235            console.info("Debug: this.textResult = " + this.textResult);
236            let stylesArr = styles.getStyles(0, this.textResult.length, StyledStringKey.FONT);
237            console.info("Debug: stylesArr.length = " + stylesArr.length);
238            for (let i = 0; i < stylesArr.length; ++i) {
239              console.info("Debug: style.start = " + stylesArr[i].start);
240              console.info("Debug: style.length = " + stylesArr[i].length);
241              console.info("Debug: style.styledKey = " + stylesArr[i].styledKey);
242              let font = stylesArr[i].styledValue as TextStyle;
243              console.info("Debug: style.fontColor = " + font.fontColor);
244              console.info("Debug: style.fontSize = " + font.fontSize);
245              console.info("Debug: style.fontFamily = " + font.fontFamily);
246              console.info("Debug: style.fontStyle = " + font.fontStyle);
247            }
248            let subStr = styles.subStyledString(0, 2);
249            console.info("Debug: subStr = " + subStr.getString());
250            this.serializeStr = "序列化";
251          } else {
252            console.info("Debug: 序列化");
253            let resultBuffer = StyledString.marshalling(this.styledString);
254            this.buff = new Uint8Array(resultBuffer);
255            this.textTitle = "调取encodeTlv接口后,序列化的结果显示:";
256            this.textResult = this.buff.toString();
257            console.info("Debug: buff = " + this.buff.toString());
258            this.serializeStr = "反序列化";
259          }
260        })
261    }.margin(10)
262  }
263
264  build() {
265    Column() {
266      Blank().margin(30)
267      Text(this.textTitle)
268      this.controllableBuild()
269    }
270  }
271}
272```
273
274![styledstring_1_sys](figures/styledstring_1_sys.gif)
275
276### 示例2 (带UserDataSpan的属性字符串序列化和反序列化)
277
278该示例通过marshalling、unmarshalling函数实现了属性字符串及其UserDataSpan序列化和反序列化的功能。
279
280```ts
281enum MyUserDataType {
282  TYPE1 = 0,
283  TYPE2
284}
285
286class MyUserData extends UserDataSpan {
287  constructor() {
288    super();
289  }
290
291  marshalling() {
292    console.log("MyUserData marshalling...");
293    const text = "MyUserData1";
294    const buffer = new ArrayBuffer(text.length + 1);
295    const uint8View = new Uint8Array(buffer);
296    // 写入类型
297    uint8View[0] = MyUserDataType.TYPE1;
298    for (let i = 1; i < text.length; i++) {
299      uint8View[i] = text.charCodeAt(i);
300    }
301    return uint8View.buffer;
302  }
303
304  unmarshalling() {
305    console.log("MyUserData unmarshalling...");
306    return new MyUserData();
307  }
308}
309
310class MyUserData2 extends UserDataSpan {
311  marshalling() {
312    console.log("MyUserData2 marshalling...");
313    const text = "MyUserData2";
314    const buffer = new ArrayBuffer(text.length + 1);
315    const uint8View = new Uint8Array(buffer);
316    uint8View[0] = MyUserDataType.TYPE2;
317    for (let i = 1; i < text.length; i++) {
318      uint8View[i] = text.charCodeAt(i);
319    }
320    return uint8View.buffer;
321  }
322
323  unmarshalling() {
324    console.log("MyUserData2 unmarshalling...");
325    return new MyUserData2();
326  }
327}
328
329@Entry
330@Component
331struct MarshallExample1 {
332  controller: TextController = new TextController();
333
334  build() {
335    Column() {
336      Text(undefined, { controller: this.controller })
337      Button("Marshall&UnMarshall")
338        .onClick(async () => {
339          let myData = new MyUserData();
340          let myData2 = new MyUserData2();
341          let myStyledString = new MutableStyledString("12345", [{
342            start: 0,
343            length: 3,
344            styledKey: StyledStringKey.USER_DATA,
345            styledValue: myData
346          }, {
347            start: 3,
348            length: 1,
349            styledKey: StyledStringKey.USER_DATA,
350            styledValue: myData2
351          }]);
352
353          let buffer = StyledString.marshalling(myStyledString, (marshallingValue: StyledStringMarshallingValue) => {
354            // 根据类型选择对应的序列化接口
355            if (marshallingValue instanceof MyUserData) {
356              console.log("StyledString.marshalling MyUserData");
357              let value = marshallingValue as MyUserData;
358              return value.marshalling();
359            } else if (marshallingValue instanceof MyUserData2) {
360              console.log("StyledString.marshalling MyUserData2");
361              let value = marshallingValue as MyUserData2;
362              return value.marshalling();
363            }
364            console.log("StyledString.marshalling default");
365            return new ArrayBuffer(10);
366          });
367
368          let newStyledString = await StyledString.unmarshalling(buffer, (value: ArrayBuffer) => {
369            // 1. 读取 type 类型,
370            // 2. 根据类型,选择对应的接口解析这个 buffer
371            const uint8View = new Uint8Array(value);
372            let type = uint8View[0];
373            console.log("unmarshalling length:" + uint8View.length);
374            if (type == MyUserDataType.TYPE1) {
375              console.log("unmarshalling type1:" + type);
376              let myUserData = new MyUserData();
377              return myUserData.unmarshalling();
378            } else if (type == MyUserDataType.TYPE2) {
379              console.log("unmarshalling type2:" + type);
380              let myUserData = new MyUserData2();
381              return myUserData.unmarshalling();
382            }
383            return new ArrayBuffer(0);
384          });
385          this.controller.setStyledString(newStyledString);
386        })
387        .fontSize(20)
388        .margin(10)
389    }
390    .justifyContent(FlexAlign.Center)
391    .width('100%')
392    .height('100%')
393  }
394}
395```
396
397![styledstring_2_sys](figures/styledstring_2_sys.gif)