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