Using Custom Fonts in ArkTS Widgets
Starting from API version 22, the ohos.graphics.text.FontCollection.getLocalInstance API has been added to obtain the local font set instance. Applications can use this local instance to load custom fonts for widgets.
How to Develop
-
Add the custom font file
xxx.ttfto theentry\src\main\resources\rawfiledirectory of the project. -
Implement page layout.
Add two buttons to the widget page. Tapping the
load fontbutton triggers loadFontSync to load the font, while tapping theunload fontbutton triggers unloadFontSync to unload it.
import { text } from '@kit.ArkGraphics2D';
@Entry
@Component
struct loadFontSyncCard {
// Use getLocalInstance to access the local font set instance.
private fc: text.FontCollection = text.FontCollection.getLocalInstance();
@State content: string = "Default font";
build() {
Column({ space: 10 }) {
Text(this.content)
.fontFamily("custom") // Declare that the component uses a custom font.
Button("load font")
.onClick(() => {
// Load the custom font file.
this.fc.loadFontSync("custom", $rawfile("xxx.ttf"));
this.content = "Custom font";
})
Button("unload font")
.onClick(() => {
this.fc.unloadFontSync("custom");
this.content = "Default font";
})
}.width("100%")
.height("100%")
.justifyContent(FlexAlign.Center)
}
}
NOTE
The local font set can load multiple custom fonts, with a total memory limit of 20 MB for all loaded fonts.
All widgets in an application share a single local font set instance. When a custom font is loaded or unloaded, the font settings for all widgets update synchronously.
Effect

你可能感兴趣的鸿蒙文章
openharmony 鸿蒙 arkts-ui-widget-adapt-faq
openharmony 鸿蒙 arkts-ui-liveform-funinteraction-development
openharmony 鸿蒙 js-ui-widget-development
openharmony 鸿蒙 arkts-ui-widget-page-animation
openharmony 鸿蒙 arkts-ui-widget-event-uiability
openharmony 鸿蒙 arkts-form-overview
openharmony 鸿蒙 arkts-ui-widget-creation
openharmony 鸿蒙 arkts-ui-widget-event-call