• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.font (Custom Font Registration)
2
3The **font** module provides APIs for registering custom fonts.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8>
9> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where [the UI context is ambiguous](../../ui/arkts-global-interface.md#ambiguous-ui-context). For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext).
10
11## Modules to Import
12
13```ts
14import { font } from '@kit.ArkUI';
15```
16
17## font.registerFont<sup>(deprecated)</sup>
18
19registerFont(options: FontOptions): void
20
21Registers a custom font with the font manager.
22
23> **NOTE**
24>
25> This API is deprecated since API version 18. You are advised to use [registerFont](js-apis-arkui-UIContext.md#registerfont) instead on the obtained [Font](js-apis-arkui-UIContext.md#font) object.
26>
27> Since API version 10, you can use the [getFont](js-apis-arkui-UIContext.md#getfont) API in [UIContext](js-apis-arkui-UIContext.md#uicontext) to obtain the [Font](js-apis-arkui-UIContext.md#font) object associated with the current UI context.
28
29**Atomic service API**: This API can be used in atomic services since API version 11.
30
31**System capability**: SystemCapability.ArkUI.ArkUI.Full
32
33**Parameters**
34
35| Name    | Type                         | Mandatory  | Description         |
36| ------- | --------------------------- | ---- | ----------- |
37| options | [FontOptions](#fontoptions) | Yes   | Information about the custom font to register.|
38
39## FontOptions
40
41Provides the information about the custom font to register.
42
43**Atomic service API**: This API can be used in atomic services since API version 11.
44
45**System capability**: SystemCapability.ArkUI.ArkUI.Full
46
47| Name        | Type    | Mandatory  | Description          |
48| ---------- | ------ | ---- | ------------ |
49| familyName | string \| [Resource](arkui-ts/ts-types.md#resource)<sup>10+</sup> | Yes   | Name of the custom font to register.  |
50| familySrc  | string \| [Resource](arkui-ts/ts-types.md#resource)<sup>10+</sup> | Yes   | Path of the custom font to register.|
51
52**Example**
53
54> **NOTE**
55>
56> Directly using **font** can lead to issue of [ambiguous UI context](../../ui/arkts-global-interface.md#ambiguous-ui-context). To avoid this, obtain the [Font](./js-apis-arkui-UIContext.md#font) object associated with the current UI context by using the [getFont](./js-apis-arkui-UIContext.md#getfont) API in [UIContext](./js-apis-arkui-UIContext.md#uicontext).
57
58```ts
59// xxx.ets
60@Entry
61@Component
62struct FontExample {
63  @State message: string = 'Hello World';
64  // iconFont example, where 0000 is the Unicode character of the specified icon. You need to obtain the Unicode character from the TTF file of the registered iconFont.
65  @State unicode: string = '\u0000';
66  @State codePoint: string = String.fromCharCode(0x0000);
67  private uiContext: UIContext = this.getUIContext();
68
69  aboutToAppear() {
70    // Both familyName and familySrc support the Resource type.
71    this.uiContext.getFont().registerFont({
72      // You are advised to use this.getUIContext().getFont().registerFont().
73      familyName: $r('app.string.font_name'),
74      familySrc: $r('app.string.font_src')
75    })
76
77    // familySrc supports the RawFile type.
78    this.uiContext.getFont().registerFont({
79      familyName: 'mediumRawFile',
80      familySrc: $rawfile('font/medium.ttf')
81    })
82
83    // Register iconFont.
84    this.uiContext.getFont().registerFont({
85      familyName: 'iconFont',
86      familySrc: '/font/iconFont.ttf'
87    })
88
89    // Both familyName and familySrc support the string type.
90    this.uiContext.getFont().registerFont({
91      familyName: 'medium',
92      familySrc: '/font/medium.ttf' // The font folder is at the same level as the pages folder.
93    })
94  }
95
96  build() {
97    Column() {
98      Text(this.message)
99        .align(Alignment.Center)
100        .fontSize(20)
101        .fontFamily('medium') // medium: name of the registered custom font. (Registered fonts such as $r('app.string.mediumFamilyName') and 'mediumRawFile' can also be used.)
102
103      // Two methods of using iconFont
104      Text(this.unicode)
105        .align(Alignment.Center)
106        .fontSize(20)
107        .fontFamily('iconFont')
108      Text(this.codePoint)
109        .align(Alignment.Center)
110        .fontSize(20)
111        .fontFamily('iconFont')
112    }.width('100%')
113  }
114}
115```
116> **NOTE**
117>
118> To use custom fonts globally in an application, register the fonts through the [windowStage.loadContent](arkts-apis-window-Window.md#loadcontent9) API in the [onWindowStageCreate](../apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) lifecycle callback in the **EntryAbility.ets** file.
119>
120> In HSP projects, avoid using relative paths to register custom fonts. For details, see [Accessing Resources in an HSP Through $r](../../quick-start/in-app-hsp.md).
121
122## font.getSystemFontList<sup>(deprecated)</sup>
123
124getSystemFontList(): Array\<string>
125
126Obtains the system font list.
127
128> **NOTE**
129>
130> This API is supported since API version 10 and deprecated since API version 18. You are advised to use [getSystemFontList](js-apis-arkui-UIContext.md#getsystemfontlist) instead on the obtained [Font](js-apis-arkui-UIContext.md#font) object.
131>
132> Since API version 10, you can use the [getFont](js-apis-arkui-UIContext.md#getfont) API in [UIContext](js-apis-arkui-UIContext.md#uicontext) to obtain the [Font](js-apis-arkui-UIContext.md#font) object associated with the current UI context.
133
134**Atomic service API**: This API can be used in atomic services since API version 11.
135
136**System capability**: SystemCapability.ArkUI.ArkUI.Full
137
138**Return value**
139
140| Type                | Description              |
141| -------------------- | ----------------- |
142| Array\<string>       | List of supported fonts. |
143
144>  **NOTE**
145>
146>  This API takes effect only on 2-in-1 devices.<br>To obtain the latest list of fonts supported by the system, use the [getSystemFontFullNamesByType](../apis-arkgraphics2d/js-apis-graphics-text.md#textgetsystemfontfullnamesbytype14) API.
147
148**Example**
149
150> **NOTE**
151>
152> Directly using **font** can lead to issue of [ambiguous UI context](../../ui/arkts-global-interface.md#ambiguous-ui-context). To avoid this, obtain the [Font](./js-apis-arkui-UIContext.md#font) object associated with the current UI context by using the [getFont](./js-apis-arkui-UIContext.md#getfont) API in [UIContext](./js-apis-arkui-UIContext.md#uicontext).
153
154<!--deprecated_code_no_check-->
155
156```ts
157// xxx.ets
158import { font } from '@kit.ArkUI';
159
160@Entry
161@Component
162struct FontExample {
163  fontList: Array<string> = new Array<string>();
164
165  build() {
166    Column() {
167      Button("getSystemFontList")
168        .width('60%')
169        .height('6%')
170        .onClick(() => {
171          this.fontList = font.getSystemFontList(); // You are advised to use the this.getUIContext().getFont().getSystemFontList() API.
172        })
173    }.width('100%')
174  }
175}
176```
177
178## font.getFontByName<sup>(deprecated)</sup>
179
180getFontByName(fontName: string): FontInfo
181
182Obtains information about a system font based on the font name.
183
184> **NOTE**
185>
186> This API is supported since API version 10 and deprecated since API version 18. You are advised to use [getFontByName](js-apis-arkui-UIContext.md#getfontbyname) instead on the obtained [Font](js-apis-arkui-UIContext.md#font) object.
187>
188> Since API version 10, you can use the [getFont](js-apis-arkui-UIContext.md#getfont) API in [UIContext](js-apis-arkui-UIContext.md#uicontext) to obtain the [Font](js-apis-arkui-UIContext.md#font) object associated with the current UI context.
189
190**Atomic service API**: This API can be used in atomic services since API version 11.
191
192**System capability**: SystemCapability.ArkUI.ArkUI.Full
193
194**Parameters**
195
196| Name     | Type     | Mandatory   | Description         |
197| ---------- | --------- | ------- | ------------ |
198| fontName   | string    | Yes     | System font name.|
199
200**Return value**
201
202| Type            | Description                         |
203| ---------------- | ---------------------------- |
204| FontInfo         | Information about the system font.    |
205
206## FontInfo<sup>10+</sup>
207
208Provides the information about the system font.
209
210**Atomic service API**: This API can be used in atomic services since API version 11.
211
212**System capability**: SystemCapability.ArkUI.ArkUI.Full
213
214| Name           | Type   | Mandatory | Description                      |
215| -------------- | ------- | ------------------------- | ------------------------- |
216| path           | string  | Yes| File path of the system font.       |
217| postScriptName | string  | Yes| PostScript name of the system font.|
218| fullName       | string  | Yes| Name of the system font.          |
219| family         | string  | Yes| Family of the system font.      |
220| subfamily      | string  | Yes| Subfamily of the system font.     |
221| weight         | number  | Yes| Weight of the system font.<br>Value range: [0, 8], with intervals of 1, corresponding to the values in the [FontWeight](../apis-arkgraphics2d/js-apis-graphics-text.md#fontweight) enum<br>Default value: **0**       |
222| width          | number  | Yes| Width of the system font.<br>Value range: [1, 9], with intervals of 1, corresponding to the values in the [FontWidth](../apis-arkgraphics2d/js-apis-graphics-text.md#fontwidth) enum   |
223| italic         | boolean | Yes| Whether the system font is italic.<br>Default value: **false**<br>**true**: The system font is italic.<br>**false**: The system font is not italic.         |
224| monoSpace      | boolean | Yes| Whether the system font is monospaced.<br>Default value: **false**<br>**true**: The system font is monospaced.<br>**false**: The system font is not monospaced.        |
225| symbolic       | boolean | Yes| Whether the system font supports symbols.<br>Default value: **false**<br>**true**: The system font supports symbols.<br>**false**: The system font does not support symbols. |
226
227**Example**
228
229> **NOTE**
230>
231> Directly using **font** can lead to issue of ambiguous UI context. To avoid this, obtain the [Font](./js-apis-arkui-UIContext.md#font) object associated with the current UI context by using the [getFont](./js-apis-arkui-UIContext.md#getfont) API in [UIContext](./js-apis-arkui-UIContext.md#uicontext).
232
233```ts
234// xxx.ets
235import { font } from '@kit.ArkUI';
236
237@Entry
238@Component
239struct FontExample {
240  fontList: Array<string> = new Array<string>();
241  uiFont = this.getUIContext().getFont();
242  fontInfo: font.FontInfo = this.uiFont.getFontByName(''); // You are advised to use the this.getUIContext().getFont().getFontByName() API.
243
244  build() {
245    Column() {
246      Button("getFontByName")
247        .onClick(() => {
248          this.fontInfo =
249            this.uiFont.getFontByName('HarmonyOS Sans Italic');
250          console.info("getFontByName(): path = " + this.fontInfo.path);
251          console.info("getFontByName(): postScriptName = " + this.fontInfo.postScriptName);
252          console.info("getFontByName(): fullName = " + this.fontInfo.fullName);
253          console.info("getFontByName(): Family = " + this.fontInfo.family);
254          console.info("getFontByName(): Subfamily = " + this.fontInfo.subfamily);
255          console.info("getFontByName(): weight = " + this.fontInfo.weight);
256          console.info("getFontByName(): width = " + this.fontInfo.width);
257          console.info("getFontByName(): italic = " + this.fontInfo.italic);
258          console.info("getFontByName(): monoSpace = " + this.fontInfo.monoSpace);
259          console.info("getFontByName(): symbolic = " + this.fontInfo.symbolic);
260        })
261    }.width('100%')
262  }
263}
264```
265
266## font.getUIFontConfig<sup>11+</sup>
267getUIFontConfig() : UIFontConfig
268
269Obtains the UI font configuration of the system.
270
271**Atomic service API**: This API can be used in atomic services since API version 12.
272
273**System capability**: SystemCapability.ArkUI.ArkUI.Full
274
275**Return value**
276| Type            | Description                         |
277| ---------------- | ---------------------------- |
278| [UIFontConfig](#uifontconfig11)     | UI font configuration of the system.         |
279
280## UIFontConfig<sup>11+</sup>
281
282Describes the UI font configuration of the system.
283
284**Atomic service API**: This API can be used in atomic services since API version 12.
285
286**System capability**: SystemCapability.ArkUI.ArkUI.Full
287| Name           | Type   | Mandatory | Description                      |
288| -------------- | ------- | ------------------------- | ------------------------- |
289| fontDir        | Array\<string>  | Yes| Path to the system font file.     |
290| generic | Array\<[UIFontGenericInfo](#uifontgenericinfo11)>  | Yes| List of supported generic font families.|
291| fallbackGroups       | Array\<[UIFontFallbackGroupInfo](#uifontfallbackgroupinfo11)>  | Yes| List of alternate generic font families.          |
292
293## UIFontGenericInfo<sup>11+</sup>
294
295Provides the list of supported generic font families.
296
297**Atomic service API**: This API can be used in atomic services since API version 12.
298
299**System capability**: SystemCapability.ArkUI.ArkUI.Full
300| Name           | Type   | Mandatory | Description                      |
301| -------------- | ------- | ------------------------- | ------------------------- |
302| family        | string | Yes| Font family name, which is the value of **family** specified in the font file.     |
303| alias        | Array\<[UIFontAliasInfo](#uifontaliasinfo11)>  | Yes| Alias list.|
304| adjust       | Array\<[UIFontAdjustInfo](#uifontadjustinfo11)>  | Yes| Weight of the font when displayed, which corresponds to the original weight.|
305
306## UIFontFallbackGroupInfo<sup>11+</sup>
307
308Provides the list of alternate generic font families.
309
310**Atomic service API**: This API can be used in atomic services since API version 12.
311
312**System capability**: SystemCapability.ArkUI.ArkUI.Full
313| Name           | Type   | Mandatory | Description                      |
314| -------------- | ------- | ------------------------- | ------------------------- |
315| fontSetName  | string | Yes| Name of the font family corresponding to the alternate fonts.     |
316| fallback        | Array\<[UIFontFallbackInfo](#uifontfallbackinfo11)>  | Yes| Alternate fonts for the font family. If **fontSetName** is **""**, it indicates that the fonts can be used as alternate fonts for all font families.|
317
318## UIFontAliasInfo<sup>11+</sup>
319
320Provides the alias list.
321
322**Atomic service API**: This API can be used in atomic services since API version 12.
323
324**System capability**: SystemCapability.ArkUI.ArkUI.Full
325| Name           | Type   | Mandatory | Description                      |
326| -------------- | ------- | ------------------------- | ------------------------- |
327| name          | string  | Yes| Alias name.     |
328| weight        | number  | Yes| Weight of the fonts included in the font family. If the value is greater than 0, the font family contains only the fonts with the specified weight. If the value is 0, the font family contains all fonts.<br>Valid values are **0**, **100**, **400**, **700**, and **900**.|
329
330## UIFontAdjustInfo<sup>11+</sup>
331
332Provides a mapping list between the original weight value of a font and the actual displayed weight value.
333
334**Atomic service API**: This API can be used in atomic services since API version 12.
335
336**System capability**: SystemCapability.ArkUI.ArkUI.Full
337| Name           | Type   | Mandatory | Description                      |
338| -------------- | ------- | ------------------------- | ------------------------- |
339| weight        | number  | Yes| Original weight of the font.<br>Valid values are **50**, **80**, **100**, and **200**.     |
340| to            | number  | Yes| Weight of the font displayed in the application.<br>Valid values are **100**, **400**, **700**, and **900**.|
341
342## UIFontFallbackInfo<sup>11+</sup>
343
344Provides the fallback font of the font set.
345
346**Atomic service API**: This API can be used in atomic services since API version 12.
347
348**System capability**: SystemCapability.ArkUI.ArkUI.Full
349| Name           | Type   | Mandatory | Description                      |
350| -------------- | ------- | ------------------------- | ------------------------- |
351| language       | string  | Yes| Language supported by the font family. The language format is BCP 47.   |
352| family         | string  | Yes| Font family name, which is the value of **family** specified in the font file.|
353
354**Example**
355
356```ts
357// xxx.ets
358import { font } from '@kit.ArkUI';
359
360@Entry
361@Component
362struct FontExample {
363  build() {
364    Column() {
365      Button("getUIFontConfig")
366        .width('60%')
367        .height('6%')
368        .margin(50)
369        .onClick(() => {
370          let fontConfig = font.getUIFontConfig();
371          console.info("font-dir -----------" + String(fontConfig.fontDir.length));
372          for (let i = 0; i < fontConfig.fontDir.length; i++) {
373            console.info(fontConfig.fontDir[i]);
374          }
375          console.info("generic-------------" + String(fontConfig.generic.length));
376          for (let i = 0; i < fontConfig.generic.length; i++) {
377            console.info("family:" + fontConfig.generic[i].family);
378            for (let j = 0; j < fontConfig.generic[i].alias.length; j++) {
379              console.info(fontConfig.generic[i].alias[j].name + " " + fontConfig.generic[i].alias[j].weight);
380            }
381            for (let j = 0; j < fontConfig.generic[i].adjust.length; j++) {
382              console.info(fontConfig.generic[i].adjust[j].weight + " " + fontConfig.generic[i].adjust[j].to);
383            }
384          }
385          console.info("fallback------------" + String(fontConfig.fallbackGroups.length));
386          for (let i = 0; i < fontConfig.fallbackGroups.length; i++) {
387            console.info("fontSetName:" + fontConfig.fallbackGroups[i].fontSetName);
388            for (let j = 0; j < fontConfig.fallbackGroups[i].fallback.length; j++) {
389              console.info("language:" + fontConfig.fallbackGroups[i].fallback[j].language + " family:" +
390              fontConfig.fallbackGroups[i].fallback[j].family);
391            }
392          }
393        })
394    }.width('100%')
395  }
396}
397```
398