• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.font (注册自定义字体)
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @hddgzw-->
5<!--Designer: @pssea-->
6<!--Tester: @jiaoaozihao-->
7<!--Adviser: @HelloCrease-->
8
9本模块提供注册自定义字体。
10
11> **说明**
12>
13> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
14>
15> 本模块功能依赖UI的执行上下文,不可在[UI上下文不明确](../../ui/arkts-global-interface.md#ui上下文不明确)的地方使用,参见[UIContext](./arkts-apis-uicontext-uicontext.md)说明。
16>
17> 推荐使用字体引擎的[loadFontSync](../apis-arkgraphics2d/js-apis-graphics-text.md#loadfontsync)接口注册自定义字体。
18
19## 导入模块
20
21```ts
22import { font } from '@kit.ArkUI';
23```
24
25## font.registerFont<sup>(deprecated)</sup>
26
27registerFont(options: FontOptions): void
28
29在字体管理中注册自定义字体。
30
31该接口为异步接口,不支持并发调用。
32
33> **说明:**
34>
35> 从API version 18开始废弃,建议使用[UIContext](arkts-apis-uicontext-uicontext.md)中的[getFont](arkts-apis-uicontext-uicontext.md#getfont)获取[Font](arkts-apis-uicontext-font.md)实例,再通过此实例调用替代方法[registerFont](arkts-apis-uicontext-font.md#registerfont)。
36>
37> 从API version 10开始,可以通过使用[UIContext](arkts-apis-uicontext-uicontext.md)中的[getFont](arkts-apis-uicontext-uicontext.md#getfont)方法获取当前UI上下文关联的[Font](arkts-apis-uicontext-font.md)对象。
38
39**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
40
41**系统能力:** SystemCapability.ArkUI.ArkUI.Full
42
43**参数:**
44
45| 参数名     | 类型                          | 必填   | 说明          |
46| ------- | --------------------------- | ---- | ----------- |
47| options | [FontOptions](#fontoptions) | 是    | 注册的自定义字体信息。 |
48
49## FontOptions
50
51注册的自定义字体信息。
52
53**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
54
55**系统能力:** SystemCapability.ArkUI.ArkUI.Full
56
57| 名称         | 类型     | 只读 | 可选   | 说明           |
58| ---------- | ------ | ---- | ---- | ------------ |
59| familyName | string \| [Resource](arkui-ts/ts-types.md#resource)<sup>10+</sup> | 否  | 否  | 设置注册的字体名称。   |
60| familySrc  | string \| [Resource](arkui-ts/ts-types.md#resource)<sup>10+</sup> | 否  | 否  | 设置注册字体文件的路径。<br/>**说明:**<br/>读取系统沙箱路径内的资源时,建议使用file://路径前缀的字符串,需要确保沙箱目录路径下的文件存在并且有可读权限。 |
61
62**示例:**
63
64> **说明**
65>
66> 直接使用font可能导致[UI上下文不明确](../../ui/arkts-global-interface.md#ui上下文不明确)的问题,推荐通过使用[UIContext](./arkts-apis-uicontext-uicontext.md)中的[getFont](./arkts-apis-uicontext-uicontext.md#getfont)方法获取当前UI上下文关联的[Font](arkts-apis-uicontext-font.md)对象。
67
68```ts
69// xxx.ets
70@Entry
71@Component
72struct FontExample {
73  @State message: string = 'Hello World';
74  // iconFont示例,假设0000为指定icon的Unicode,实际需要开发者从注册的iconFont的ttf文件里面获取Unicode
75  @State unicode: string = '\u0000';
76  @State codePoint: string = String.fromCharCode(0x0000);
77  private uiContext: UIContext = this.getUIContext();
78
79  aboutToAppear() {
80    // familyName和familySrc都支持系统Resource
81    this.uiContext.getFont().registerFont({
82      // 建议使用 this.getUIContext().getFont().registerFont()接口
83      // 'app.string.font_name'和'app.string.font_src'仅作示例,请替换为实际使用资源字符串
84      familyName: $r('app.string.font_name'),
85      familySrc: $r('app.string.font_src')
86    })
87
88    // familySrc支持RawFile
89    this.uiContext.getFont().registerFont({
90      familyName: 'mediumRawFile',
91      familySrc: $rawfile('font/medium.ttf')// 'font/medium.ttf'仅作示例,请替换为实际使用资源字体文件
92    })
93
94    // 注册iconFont
95    this.uiContext.getFont().registerFont({
96      familyName: 'iconFont',
97      familySrc: '/font/iconFont.ttf'
98    })
99
100    // familyName和familySrc都支持string
101    this.uiContext.getFont().registerFont({
102      familyName: 'medium',
103      familySrc: '/font/medium.ttf' // font文件夹与pages目录同级
104    })
105  }
106
107  build() {
108    Column() {
109      Text(this.message)
110        .align(Alignment.Center)
111        .fontSize(20)
112        .fontFamily('medium') // medium:注册自定义字体的名字($r('app.string.mediumFamilyName')、'mediumRawFile'等已注册字体也能正常使用)
113
114      // 使用iconFont的两种方式
115      Text(this.unicode)
116        .align(Alignment.Center)
117        .fontSize(20)
118        .fontFamily('iconFont')
119      Text(this.codePoint)
120        .align(Alignment.Center)
121        .fontSize(20)
122        .fontFamily('iconFont')
123    }.width('100%')
124  }
125}
126```
127> **说明:**
128>
129> 应用若需全局使用自定义字体,请在EntryAbility.ets文件的[onWindowStageCreate](../apis-ability-kit/js-apis-app-ability-uiAbility.md#onwindowstagecreate)生命周期中,通过[windowStage.loadContent](arkts-apis-window-Window.md#loadcontent9)回调注册。
130>
131> 在HSP工程中,不推荐采用相对路径的方式注册自定义字体,详见[通过$r访问HSP中的资源](../../quick-start/in-app-hsp.md)。
132
133## font.getSystemFontList<sup>(deprecated)</sup>
134
135getSystemFontList(): Array\<string>
136
137获取风格字体列表。
138
139该接口仅在PC/2in1设备上生效,在其他设备上返回空数组。
140
141推荐使用[getSystemFontFullNamesByType](../apis-arkgraphics2d/js-apis-graphics-text.md#textgetsystemfontfullnamesbytype14)接口获取系统最新支持的字体列表数据。
142
143> **说明:**
144>
145> 从API version 10开始支持,从API version 18开始废弃,建议使用[UIContext](arkts-apis-uicontext-uicontext.md)中的[getFont](arkts-apis-uicontext-uicontext.md#getfont)获取[Font](arkts-apis-uicontext-font.md)实例,再通过此实例调用替代方法[getSystemFontList](arkts-apis-uicontext-font.md#getsystemfontlist)。
146>
147> 从API version 10开始,可以通过使用[UIContext](arkts-apis-uicontext-uicontext.md)中的[getFont](arkts-apis-uicontext-uicontext.md#getfont)方法获取当前UI上下文关联的[Font](arkts-apis-uicontext-font.md)对象。
148
149**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
150
151**系统能力:** SystemCapability.ArkUI.ArkUI.Full
152
153**返回值:**
154
155| 类型                 | 说明               |
156| -------------------- | ----------------- |
157| Array\<string>       | 系统的字体名列表。  |
158
159**示例:**
160
161> **说明**
162>
163> 直接使用font可能导致[UI上下文不明确](../../ui/arkts-global-interface.md#ui上下文不明确)的问题,推荐通过使用[UIContext](arkts-apis-uicontext-uicontext.md)中的[getFont](arkts-apis-uicontext-uicontext.md#getfont)方法获取当前UI上下文关联的[Font](arkts-apis-uicontext-font.md)对象。
164
165<!--deprecated_code_no_check-->
166
167```ts
168// xxx.ets
169import { font } from '@kit.ArkUI';
170
171@Entry
172@Component
173struct FontExample {
174  fontList: Array<string> = new Array<string>();
175
176  build() {
177    Column() {
178      Button("getSystemFontList")
179        .width('60%')
180        .height('6%')
181        .onClick(() => {
182          this.fontList = font.getSystemFontList(); // 建议使用 this.getUIContext().getFont().getSystemFontList()接口
183        })
184    }.width('100%')
185  }
186}
187```
188
189## font.getFontByName<sup>(deprecated)</sup>
190
191getFontByName(fontName: string): FontInfo
192
193根据传入的系统字体名称获取系统字体的相关信息。
194
195> **说明:**
196>
197> 从API version 10开始支持,从API version 18开始废弃,建议使用[UIContext](arkts-apis-uicontext-uicontext.md)中的[getFont](arkts-apis-uicontext-uicontext.md#getfont)获取[Font](arkts-apis-uicontext-font.md)实例,再通过此实例调用替代方法[getFontByName](arkts-apis-uicontext-font.md#getfontbyname)。
198>
199> 从API version 10开始,可以通过使用[UIContext](arkts-apis-uicontext-uicontext.md)中的[getFont](arkts-apis-uicontext-uicontext.md#getfont)方法获取当前UI上下文关联的[Font](arkts-apis-uicontext-font.md)对象。
200
201**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
202
203**系统能力:** SystemCapability.ArkUI.ArkUI.Full
204
205**参数:**
206
207| 参数名      | 类型      | 必填    | 说明          |
208| ---------- | --------- | ------- | ------------ |
209| fontName   | string    | 是      | 系统的字体名。 |
210
211**返回值:**
212
213| 类型             | 说明                          |
214| ---------------- | ---------------------------- |
215| FontInfo         | 字体的详细信息。     |
216
217## FontInfo<sup>10+</sup>
218
219字体的详细信息。
220
221**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
222
223**系统能力:** SystemCapability.ArkUI.ArkUI.Full
224
225| 名称            | 类型    | 只读 | 可选  | 说明                       |
226| -------------- | ------- | ------------------------- | ------------------------- | ------------------------- |
227| path           | string  | 否 | 否 | 系统字体的文件路径。        |
228| postScriptName | string  | 否 | 否 | 系统字体的postScript名称。 |
229| fullName       | string  | 否 | 否 | 系统字体的名称。           |
230| family         | string  | 否 | 否 | 系统字体的字体家族。       |
231| subfamily      | string  | 否 | 否 | 系统字体的子字体家族。      |
232| weight         | number  | 否 | 否 | 系统字体的字重。<br/>取值范围:[100,900],取值间隔为100,分别对应[FontWeight](../apis-arkgraphics2d/js-apis-graphics-text.md#fontweight)枚举中的值。<br/>默认值:100        |
233| width          | number  | 否 | 否 | 系统字体的宽度。<br/>取值范围:[1,9],取值间隔为1,分别对应[FontWidth](../apis-arkgraphics2d/js-apis-graphics-text.md#fontwidth)枚举中的值。    |
234| italic         | boolean | 否 | 否 | 系统字体是否倾斜。<br/>默认值:false<br/>值为true,表示斜体字体,值为false,表示非斜体字体。          |
235| monoSpace      | boolean | 否 | 否 | 系统字体是否等宽。<br/>默认值:false<br/>值为true,表示等宽字体,值为false,表示非等宽字体。         |
236| symbolic       | boolean | 否 | 否 | 系统字体是否支持符号字体。<br/>默认值:false<br/>值为true,表示支持符号字体,值为false,表示不支持符号字体。  |
237
238**示例:**
239
240> **说明**
241>
242> 直接使用font可能导致实例不明确的问题,推荐通过使用[UIContext](./arkts-apis-uicontext-uicontext.md)中的[getFont](./arkts-apis-uicontext-uicontext.md#getfont)方法获取当前UI上下文关联的[Font](arkts-apis-uicontext-font.md)对象。
243
244```ts
245// xxx.ets
246import { font } from '@kit.ArkUI';
247
248@Entry
249@Component
250struct FontExample {
251  fontList: Array<string> = new Array<string>();
252  uiFont = this.getUIContext().getFont();
253  fontInfo: font.FontInfo = this.uiFont.getFontByName(''); // 建议使用 this.getUIContext().getFont().getFontByName()接口
254
255  build() {
256    Column() {
257      Button("getFontByName")
258        .onClick(() => {
259          this.fontInfo =
260            this.uiFont.getFontByName('HarmonyOS Sans Italic');
261          console.info("getFontByName(): path = " + this.fontInfo.path);
262          console.info("getFontByName(): postScriptName = " + this.fontInfo.postScriptName);
263          console.info("getFontByName(): fullName = " + this.fontInfo.fullName);
264          console.info("getFontByName(): family = " + this.fontInfo.family);
265          console.info("getFontByName(): subfamily = " + this.fontInfo.subfamily);
266          console.info("getFontByName(): weight = " + this.fontInfo.weight);
267          console.info("getFontByName(): width = " + this.fontInfo.width);
268          console.info("getFontByName(): italic = " + this.fontInfo.italic);
269          console.info("getFontByName(): monoSpace = " + this.fontInfo.monoSpace);
270          console.info("getFontByName(): symbolic = " + this.fontInfo.symbolic);
271        })
272    }.width('100%')
273  }
274}
275```
276
277## font.getUIFontConfig<sup>11+</sup>
278getUIFontConfig() : UIFontConfig
279
280获取系统的UI字体配置。
281
282**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
283
284**系统能力:** SystemCapability.ArkUI.ArkUI.Full
285
286**返回值:**
287| 类型             | 说明                          |
288| ---------------- | ---------------------------- |
289| [UIFontConfig](#uifontconfig11)     | 系统的UI字体配置信息。          |
290
291## UIFontConfig<sup>11+</sup>
292
293系统的UI字体配置信息。
294
295**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
296
297**系统能力:** SystemCapability.ArkUI.ArkUI.Full
298| 名称            | 类型    | 只读 | 可选  | 说明                       |
299| -------------- | ------- | ------------------------- | ------- | ------------------------- |
300| fontDir        | Array\<string>  | 否 | 否 | 系统字体文件所在的路径。      |
301| generic | Array\<[UIFontGenericInfo](#uifontgenericinfo11)>  | 否 | 否 | 系统所支持的通用字体集列表。 |
302| fallbackGroups       | Array\<[UIFontFallbackGroupInfo](#uifontfallbackgroupinfo11)>  | 否 | 否 | 备用字体集。           |
303
304## UIFontGenericInfo<sup>11+</sup>
305
306系统所支持的通用字体集列表。
307
308**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
309
310**系统能力:** SystemCapability.ArkUI.ArkUI.Full
311| 名称            | 类型    | 只读 | 可选  | 说明                       |
312| -------------- | ------- | ------------------------- | ------------------------- | ------------------------- |
313| family        | string | 否 | 否 | 字体集名,字体文件中指定的"family"值。      |
314| alias        | Array\<[UIFontAliasInfo](#uifontaliasinfo11)>  | 否 | 否 | 别名列表。 |
315| adjust       | Array\<[UIFontAdjustInfo](#uifontadjustinfo11)>  | 否 | 否 | 字体原本的weight值对应需显示的值。 |
316
317## UIFontFallbackGroupInfo<sup>11+</sup>
318
319备用字体集。
320
321**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
322
323**系统能力:** SystemCapability.ArkUI.ArkUI.Full
324| 名称            | 类型    | 只读 | 可选  | 说明                       |
325| -------------- | ------- | ------------------------- | ------------------------- | ------------------------- |
326| fontSetName  | string | 否 | 否 | 备用字体集所对应的字体集名称。      |
327| fallback        | Array\<[UIFontFallbackInfo](#uifontfallbackinfo11)>  | 否 | 否 | 表示以下列表为该字体集的备用字体,如果fontSetName为"",表示可以作为所有字体集的备用字体。 |
328
329## UIFontAliasInfo<sup>11+</sup>
330
331别名列表。
332
333**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
334
335**系统能力:** SystemCapability.ArkUI.ArkUI.Full
336| 名称            | 类型    | 只读 | 可选  | 说明                       |
337| -------------- | ------- | ------- | ------------------------- | ------------------------- |
338| name          | string  | 否 | 否 | 别名名称。      |
339| weight        | number  | 否 | 否 | 当weight>0时表示此字体集只包含所指定weight的字体,当weight=0时,表示此字体集包含所有字体。<br/>可返回的值有0、100、400、700、900。 |
340
341## UIFontAdjustInfo<sup>11+</sup>
342
343字体原本的weight值和显示实际值的映射列表。
344
345**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
346
347**系统能力:** SystemCapability.ArkUI.ArkUI.Full
348| 名称            | 类型    | 只读 | 可选  | 说明                       |
349| -------------- | ------- | ------- | ------------------------- | ------------------------- |
350| weight        | number  | 否 | 否 | 字体原本的weight值。<br/>可返回的值有50、80、100、200。      |
351| to            | number  | 否 | 否 | 字体在应用中显示的weight值。<br/>可返回的值有100、400、700、900。 |
352
353## UIFontFallbackInfo<sup>11+</sup>
354
355该字体集的备用字体。
356
357**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
358
359**系统能力:** SystemCapability.ArkUI.ArkUI.Full
360| 名称            | 类型    | 只读 | 可选  | 说明                       |
361| -------------- | ------- | ------- | ------------------------- | ------------------------- |
362| language       | string  | 否 | 否 | 字体集所支持的语言类型,语言格式为bcp47。    |
363| family         | string  | 否 | 否 | 字体集名,字体文件中指定的"family"值。 |
364
365**示例:**
366
367```ts
368// xxx.ets
369import { font } from '@kit.ArkUI';
370
371@Entry
372@Component
373struct FontExample {
374  build() {
375    Column() {
376      Button("getUIFontConfig")
377        .width('60%')
378        .height('6%')
379        .margin(50)
380        .onClick(() => {
381          let fontConfig = font.getUIFontConfig();
382          console.info("font-dir -----------" + String(fontConfig.fontDir.length));
383          for (let i = 0; i < fontConfig.fontDir.length; i++) {
384            console.info(fontConfig.fontDir[i]);
385          }
386          console.info("generic-------------" + String(fontConfig.generic.length));
387          for (let i = 0; i < fontConfig.generic.length; i++) {
388            console.info("family:" + fontConfig.generic[i].family);
389            for (let j = 0; j < fontConfig.generic[i].alias.length; j++) {
390              console.info(fontConfig.generic[i].alias[j].name + " " + fontConfig.generic[i].alias[j].weight);
391            }
392            for (let j = 0; j < fontConfig.generic[i].adjust.length; j++) {
393              console.info(fontConfig.generic[i].adjust[j].weight + " " + fontConfig.generic[i].adjust[j].to);
394            }
395          }
396          console.info("fallback------------" + String(fontConfig.fallbackGroups.length));
397          for (let i = 0; i < fontConfig.fallbackGroups.length; i++) {
398            console.info("fontSetName:" + fontConfig.fallbackGroups[i].fontSetName);
399            for (let j = 0; j < fontConfig.fallbackGroups[i].fallback.length; j++) {
400              console.info("language:" + fontConfig.fallbackGroups[i].fallback[j].language + " family:" +
401              fontConfig.fallbackGroups[i].fallback[j].family);
402            }
403          }
404        })
405    }.width('100%')
406  }
407}
408```
409