目录

How do I load and use custom fonts?

  1. Use @ohos.font (Custom Font Registration).
  2. Set the font family for the text. The code snippet is as follows:
    // xxx.ets
    import { Font } from '@kit.ArkUI';
    
    @Entry
    @Component
    struct FontExample {
      @State message: string = 'Hello World';
    
      aboutToAppear() {
        // Register in black font
        let font: Font = this.getUIContext().getFont()
        font.registerFont({
          familyName: 'Condensed_Black', // Registered font name
          familySrc: '/font/Sans_Condensed_Black.ttf' // The font folder is at the same level as the pages directory
        })
    
        // Register in black oblique font
        font.registerFont({
          familyName: 'Condensed_Black_Italic', // Registered font name
          familySrc: '/font/Sans_Condensed_Black_Italic.ttf' // The font folder is at the same level as the pages directory
        })
      }
    
      build() {
        Column() {
          Text(this.message)
            .align(Alignment.Center)
            .fontSize(50)
            .fontFamily('Condensed_Black') // Use black font
          Text(this.message)
            .align(Alignment.Center)
            .fontSize(50)
            .fontFamily('Condensed_Black_Italic') // Use black oblique font
          Text(this.message)
            .align(Alignment.Center)
            .fontSize(50)
        }
        .width('100%')
        .margin({ top: 30 })
      }
    }

The figure below shows the preview.