DEV Community

HarmonyOS
HarmonyOS

Posted on

How to deal with custom fonts that cannot be used globally

Read the original article:How to deal with custom fonts that cannot be used globally

Problem Description

Failed to register the custom font for the app globally.

  • Expected result: The custom font can be successfully used in the application.
  • Actual result: After registering a custom font, the display effect is the same as the default font.

The code of the problem is as follows:

  • Register the font.
  // Registering iconFont
  this.getUIContext().getFont().registerFont({
    familyName: 'iconFont',
    // Custom fonts are stored in the font folder under rawfile.
    familySrc: $rawfile('font/XXXX.TTF')
  });
Enter fullscreen mode Exit fullscreen mode
  • Use fonts.
  @Entry
  @Component
  struct Index {
    build() {
      Column() {
        // Text using custom fonts
        Text('Icon Fonts')
          .fontSize(30)
          .fontFamily('iconfont');
        // Text using the default font.
        Text('Icon Fonts')
          .fontSize(30);
      }.width('100%');
    }
  }
Enter fullscreen mode Exit fullscreen mode

Background Knowledge

For details, see the official document @ ohos.font (Register Custom Font).

Problem Analysis

When identifying the reason why a custom font cannot be used, you should first confirm whether the font registration information is configured correctly. If the font registration information is correctly configured but the font still cannot be displayed properly, you need to further check whether the lifecycle status of the font instance is within the valid range.

Analysis Conclusion

  1. The registration information is incorrect. Check the information according to the API document registerFont.
  2. The registration lifecycle is incorrect. When the custom font registration information is correctly filled out but still cannot be used, it is because uses custom fonts globally. In this case, you need to register through the windowStage.loadContent callback in the onWindowStageCreate lifecycle of the EntryAbility.ets file. For details, refer to the loadContent callback method.

Solution

According to the fault locating method, you can perform the following operations:

  1. Check the registration information.
    Check whether the registration information is correct.
    Ensure that the registration path is correct. For example, if you save the custom font in the font folder of the rawfile, the path must be correct when you use the font in the code. $rawfile('font/XXX.ttf')

  2. Check the lifecycle.
    According to the fault locating method, check whether the lifecycle of the globally defined font is correct.

  • Register the custom font in onWindowStageCreate of entryability.ets.
   onWindowStageCreate(windowStage: window.WindowStage): void {
     // Main window is created, set main page for this ability
     hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
     windowStage.loadContent('pages/Index', (err) => {
       if (err.code) {
         hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
         return;
       }
       windowStage.getMainWindow().then(res => {
         // Registering a global custom font that takes effect globally.
         const uiCtc = res.getUIContext();
         uiCtc.getFont().registerFont({
           familyName: 'iconfont',
           // The font file is stored in the rawfile directory. You need to configure the font resource file.
           familySrc: $rawfile('font/HarmonyOS_Sans_SC_Thin.ttf')
         });
       });
       hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
     });
   }
Enter fullscreen mode Exit fullscreen mode
  • Index file.
   @Entry
   @Component
   struct Index {
     build() {
       Column() {
         // Text using custom fonts
         Text('Icon Fonts')
           .fontSize(30)
           .fontFamily('iconfont');
         // Text using the default font.
         Text('Icon Fonts')
           .fontSize(30);
       }.justifyContent(FlexAlign.Center)
       .height('100%')
       .width('100%');
     }
   }
Enter fullscreen mode Exit fullscreen mode
  • Effect preview:

cke_7382.png

Other precautions:

  • The font file needs to be downloaded to for local use , and the Unicode encoding must be obtained correctly.
  • During compilation, needs to be debugged on a real device or simulator. cannot be properly displayed on the previewer.

FAQs

Q: The custom font is globally registered in onWindowStageCreate. Is there a way to globally set the custom font for an application?
A: You can use ApplicationContext.setFont to globally set the font for the entire project. You can call ApplicationContext.setFont() in the windowStage.loadContent method.

Summary

@ ohos.font can be used to register page-level fonts or global fonts. Global fonts need to be registered through the callback of windowStage.loadContent.

Written by Simay Ayberik

Top comments (0)