Swapping Fonts at Runtime
Fonts can be loaded dynamically at runtime. This allows you to localize your Rive content without increasing the file size of the exported .riv file. For more information, see Loading Assets.Fallback Fonts
When rendering text, not all glyphs (characters) may be available in the active font. This commonly occurs when:- Using custom fonts that don’t support all languages or Unicode ranges
- The embedded font is a subset of the font
- User-generated or dynamic text contains unexpected characters
On Android, font sizes specified for fallback fonts are ignored. Instead, the platform selects system fonts that best match the styling and animation of the text run at runtime.
If no fallback fonts are registered, a default system font (“sans-serif”) with a regular weight (400, NORMAL) and normal style will be used.
Fonts class provides ways to handle and customize fonts, including retrieving system fonts, defining font options, and finding fallback fonts based on specific characteristics.
1. Setting a Fallback Font
With v9.12.0, the runtime provides a new API to match missing fonts against a specific weight by extending theFontFallbackStrategy interface.
This interface contains a single method:
FontFallbackStrategy.stylePicker.
Example:
FontBytes (`ByteArray`). The runtime attempts to match the character using the fonts in the list in a first-in, first-out (FIFO) order.
Fallback fonts can also be set using Rive.setFallbackFont(), with optional font preferences defined in Fonts.FontOpts. These fonts are tried only after attempting the ones returned by FontFallbackStrategy.getFont().
2. Font.FontOpts - Font Options
Defines the font characteristics when selecting a fallback font.- Parameters
familyName: Name of the font family (e.g., “Roboto”, “NotoSansThai-Regular.ttf”). Defaults tonulllang: Optional language specification. Defaults tonullweight: Font weight usingFonts.Weight(e.g.,Fonts.Weight.NORMAL,Fonts.Weight.BOLD). Default isWeight.NORMALstyle: Font style, eitherFonts.Font.STYLE_NORMALorFonts.Font.STYLE_ITALIC. Default isSTYLE_NORMAL- Default example
3. Retrieving a Fallback Font
UseFontHelper.getFallbackFont() to find a suitable fallback font based on specified options. Returns a Fonts.Font object or null if no match is found.
Example:
4. Getting Font File and Bytes
FontHelper.getFontFile(font: Fonts.Font): Retrieves the file for the specified font.FontHelper.getFontBytes(font: Fonts.Font): Reads the font file and returns its bytes.
5. Fonts.Weight - Font Weight
Represents the font weight, allowing values from 0 to 1000.- Predefined Weights
Fonts.Weight.NORMAL(400)Fonts.Weight.BOLD(700)
6. Fonts.Style - Font Style
Represents the font style, allowing “normal” and “italic”- Predefined Styles
Fonts.Font.STYLE_NORMALFonts.Font.STYLE_ITALIC
7. Getting System Fonts
FontHelper.getSystemFonts(): Returns a map of all available system font families.