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