Reference version

This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

Expo 字体 iconExpo 字体

一个允许在运行时加载字体并在 React Native 组件中使用它们的库。

Android
iOS
tvOS
Web
Included in Expo Go

expo-font 允许从 web 加载字体,并在 React Native 组件中使用它们。更多详细用法请参阅 字体 指南。

安装

Terminal
- npx expo install expo-font
- yarn expo install expo-font
- pnpm expo install expo-font
- bun expo install expo-font

If you are installing this in an existing React Native app, make sure to install expo in your project.

app config 中的配置

向你的应用添加字体有两种方式:使用 expo-font 配置插件(推荐用于 Android 和 iOS)或在运行时加载它们(适用于包括 web 在内的所有平台)。

在 Android 和 iOS 上,该插件允许你在构建时嵌入字体文件,这比 useFonts 或 loadAsync 更高效。设置好配置插件并运行 prebuild 之后,你就可以立即渲染自定义字体。插件可以通过不同方式进行配置,关于如何使用,请参阅 字体 指南。

Example app.json with config plugin

app.json
{ "expo": { "plugins": [ [ "expo-font", { "fonts": ["./path/to/file.ttf"], "android": { "fonts": [ { "fontFamily": "Source Serif 4", "fontDefinitions": [ { "path": "./path/to/SourceSerif4-ExtraBold.ttf", "weight": 800 } ] }, { "fontFamily": "Roboto Flex", "path": "./path/to/RobotoFlex.ttf", "fontDefinitions": [ { "weight": 400 }, { "weight": 700 }, { "weight": 400, "style": "italic", "axes": { "slnt": -10 } } ] } ] }, "ios": { "fonts": ["./path/to/SourceSerif4-ExtraBold.ttf"] } } ] ] } }

Configurable properties

NameDefaultDescription
fonts[]

要链接到原生项目的字体定义数组。路径应相对于项目根目录。在 Android 上,文件名会成为字体族名称。在 iOS 上,字体族名称始终直接取自字体文件,可能与文件名不同——请遵循 命名建议 或使用 getLoadedFonts 查看可用的字体。

android{}

包含 fonts 字体定义数组的对象,用于将字体链接到 Android 上的原生项目。使用 fonts 中的对象语法,以自定义族名称嵌入 xml 字体。

ios{}

包含 fonts 字体文件路径数组的对象,用于将字体链接到 iOS 上的原生项目。字体族名称直接取自字体文件。

Are you using this library in an existing React Native app?

用法

如果你不想使用 配置插件,可以像下面的代码片段所示,使用 useFonts hook 在运行时加载字体:

加载并使用自定义字体示例
import { useFonts } from 'expo-font'; import * as SplashScreen from 'expo-splash-screen'; import { useEffect } from 'react'; import { Text, View, StyleSheet } from 'react-native'; SplashScreen.preventAutoHideAsync(); export default function App() { // 仅当你无法使用配置插件时,才使用 `useFonts`。 const [loaded, error] = useFonts({ 'Inter-Black': require('./assets/fonts/Inter-Black.otf'), }); useEffect(() => { if (loaded || error) { SplashScreen.hideAsync(); } }, [loaded, error]); if (!loaded && !error) { return null; } return ( <View style={styles.container}> <Text style={{ fontFamily: 'Inter-Black', fontSize: 30 }}>Inter Black</Text> <Text style={{ fontSize: 30 }}>平台默认值</Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, });

可变字体

上方示例中的 Roboto Flex 条目是一个可变字体:一个文件包含多种字形。你可以通过 fontWeight 和 fontStyle 样式属性选择字形。可变字体也适用于 useFonts。更多信息请参阅字体指南中的可变字体。

多种字重和样式

一个字体族也可以包含多个静态字体文件,例如常规、粗体和斜体字形。若要在同一个 fontFamily 名称下加载它们,请向 useFonts 或 loadAsync 传递 FontFamilyDefinition 数组,而不是映射表。然后通过 fontWeight 和 fontStyle 样式属性选择字形。更多信息请参阅字体指南中的为一个字体族加载多种字重和样式。

API

import * as Font from 'expo-font';

Constants

useFonts

Android
iOS
tvOS
Web

Type: UseFontHook

Load a map of fonts at runtime with loadAsync. This returns true if the fonts are loaded and ready to use. It also returns an error if something went wrong, to use in development.

Example

const [loaded, error] = useFonts({ 'Inter-Black': require('./assets/fonts/Inter-Black.otf'), });

On web, loading multiple weights or styles of the same family lets the browser select the correct face with the CSS font-weight and font-style properties:

const [loaded, error] = useFonts([ { fontFamily: 'Inter', fontDefinitions: [ { path: require('./assets/fonts/Inter-Regular.otf'), weight: 400 }, { path: require('./assets/fonts/Inter-Italic.otf'), weight: 400, style: 'italic' }, { path: require('./assets/fonts/Inter-Bold.otf'), weight: 700 }, ], }, ]);

Methods

getLoadedFonts()

Android
iOS
tvOS
Web

Synchronously get all the fonts that have been loaded. This includes fonts that were bundled at build time using the config plugin, as well as those loaded at runtime using loadAsync.

Returns:
string[]

Returns array of strings which you can use as fontFamily style prop.

isLoaded(fontFamily)

Android
iOS
tvOS
Web
ParameterTypeDescription
fontFamilystring

The name used to load the FontResource.


Synchronously detect if the font for fontFamily has finished loading.

Returns:
boolean

Returns true if the font has fully loaded.

isLoading(fontFamily)

Android
iOS
tvOS
Web
ParameterTypeDescription
fontFamilystring

The name used to load the FontResource.


Synchronously detect if the font for fontFamily is still being loaded.

Returns:
boolean

Returns true if the font is still loading.

loadAsync(fontFamilyOrFontMap, source)

Android
iOS
tvOS
Web
ParameterTypeDescription
fontFamilyOrFontMapFontMap

String, map of values that can be used as the fontFamily style prop with React Native Text elements, or an array of FontFamilyDefinitions for loading multiple faces per family.

source(optional)FontSource

The font asset that should be loaded into the fontFamily namespace.


An efficient method for loading fonts from static or remote resources which can then be used with the platform's native text elements. In the browser, this generates a @font-face block in a shared style sheet for fonts. No CSS is needed to use this method.

Returns:
Promise<void>

Returns a promise that fulfils when the font has loaded. Often you may want to wrap the method in a try/catch/finally to ensure the app continues if the font fails to load.

renderToImageAsync(glyphs, options)

Android
iOS
ParameterTypeDescription
glyphsstring

Text to be exported.

options(optional)RenderToImageOptions

RenderToImageOptions.


Creates an image with provided text.

Promise which fulfils with image metadata.

Interfaces

RenderToImageOptions

Android
iOS
tvOS
Web
PropertyTypeDescription
color(optional)string

Font color

Default:'black'
fontFamily(optional)string

Font family name.

Default:system default
lineHeight(optional)number

Line height of the text. Accepts number in dp units.

size(optional)number

Size of the font.

Default:24

RenderToImageResult

Android
iOS
tvOS
Web
PropertyTypeDescription
heightnumber

Image height in dp.

scalenumber

Scale factor of the image. Multiply the dp dimensions by this value to get the dimensions in pixels.

uristring

The file uri to the image.

widthnumber

Image width in dp.

Types

FontFaceDefinition

Android
iOS
tvOS
Web

A single font face that belongs to a FontFamilyDefinition. Use weight and style to distinguish faces of the same fontFamily, for example the bold or italic cut of a typeface.

PropertyTypeDescription
display(optional)FontDisplay
Only for: 
Web

Sets the font-display property for this face in the browser.

pathFontSource

The font asset to load for this face, in any format accepted by FontSource.

style(optional)'normal' | 'italic' | 'oblique'

On Android, the declared style used to select this face. When unset, the style read from the font file applies. On API levels below 29, only the family's default face (closest to a regular, upright weight and style) is loaded.

On iOS, this value isn't used to select the face; iOS reads the style embedded in the font file's own metadata instead.

On web, maps to the CSS font-style property. Leave unset for a variable font file that covers both upright and italic/oblique styles — a single value restricts the face to only that style.

weight(optional)number | string

On Android, the declared weight used to select this face. When unset, the weight read from the font file applies, and a variable font face keeps its whole wght axis — fontWeight renders the matching instance. Setting a weight on a variable font face pins it to that single instance. On API levels below 29, only the family's default face (closest to a regular, upright weight and style) is loaded.

On iOS, this value isn't used to select the face; iOS reads the weight embedded in the font file's own metadata instead.

On web, maps to the CSS font-weight property. A variable font file can also declare a weight range as '<min> <max>', for example '100 900'. Leave unset for a variable font file that covers its full range of weights — a single value restricts the face to only that weight. A range is ignored on Android, which keeps the variable font's whole wght axis, and on iOS, which reads the weight from the font file instead.

FontFamilyDefinition

Android
iOS
tvOS
Web

Groups one or more FontFaceDefinitions under a single fontFamily name. Use this to load multiple weights or styles (for example regular, bold, and italic) of the same typeface so the browser can select the correct face with the CSS font-weight and font-style properties.

PropertyTypeDescription
fontDefinitionsFontFaceDefinition[]

The faces (for example different weights or styles) that make up fontFamily.

fontFamilystring

The name used as the fontFamily style prop with React Native Text elements.

FontMap

Android
iOS
tvOS
Web

Literal type: union

The value accepted by useFonts and loadAsync: a single fontFamily name, a map of fontFamily names to FontSources, or an array of FontFamilyDefinitions for loading multiple faces per family.

Acceptable values are: string | Record<string, FontSource>

FontResource

Android
iOS
tvOS
Web

An object used to dictate the resource that is loaded into the provided font namespace when used with loadAsync.

PropertyTypeDescription
default(optional)string
-
display(optional)FontDisplay
Only for: 
Web

Sets the font-display property for a given typeface in the browser.

style(optional)'normal' | 'italic' | 'oblique'

Sets the face's style when the resource is the path of a FontFaceDefinition and the face doesn't declare its own. Outside of a font family definition, only the browser uses this value, as the CSS font-style property.

uri(optional)string | number
-
weight(optional)number | string

Sets the face's weight when the resource is the path of a FontFaceDefinition and the face doesn't declare its own. Outside of a font family definition, only the browser uses this value, as the CSS font-weight property.

FontSource

Android
iOS
tvOS
Web

Literal type: union

The different types of assets you can provide to the loadAsync() function. A font source can be a URI, a module ID, or an Expo Asset.

Acceptable values are: string | number | Asset | FontResource

ServerFontResourceDescriptor

Android
iOS
tvOS
Web

Type: object shaped as below:

PropertyTypeDescription
cssstring
-
idstring
-
type'style'
-

Or object shaped as below:

PropertyTypeDescription
as'font'
-
crossOrigin(optional)'anonymous' | 'use-credentials' | undefined
-
hrefstring
-
rel'preload'
-
type'link'
-

Enums

FontDisplay

Web

Sets the font-display for a given typeface. The default font value on web is FontDisplay.AUTO. Even though setting the fontDisplay does nothing on native platforms, the default behavior emulates FontDisplay.SWAP on flagship devices like iOS, Samsung, Pixel, etc. Default functionality varies on One Plus devices. In the browser this value is set in the generated @font-face CSS block and not as a style property meaning you cannot dynamically change this value based on the element it's used in.

AUTO

FontDisplay.AUTO = "auto"

(Default) The font display strategy is defined by the user agent or platform. This generally defaults to the text being invisible until the font is loaded. Good for buttons or banners that require a specific treatment.

BLOCK

FontDisplay.BLOCK = "block"

The text will be invisible until the font has loaded. If the font fails to load then nothing will appear - it's best to turn this off when debugging missing text.

FALLBACK

FontDisplay.FALLBACK = "fallback"

Splits the behavior between SWAP and BLOCK. There will be a 100ms timeout where the text with a custom font is invisible, after that the text will either swap to the styled text or it'll show the unstyled text and continue to load the custom font. This is good for buttons that need a custom font but should also be quickly available to screen-readers.

OPTIONAL

FontDisplay.OPTIONAL = "optional"

This works almost identically to FALLBACK, the only difference is that the browser will decide to load the font based on slow connection speed or critical resource demand.

SWAP

FontDisplay.SWAP = "swap"

Fallback text is rendered immediately with a default font while the desired font is loaded. This is good for making the content appear to load instantly and is usually preferred.

错误代码

代码描述
ERR_FONT_API传递给 loadAsync 的参数无效。
ERR_FONT_SOURCE所提供的资源类型不正确。
ERR_WEB_ENVIRONMENT浏览器的 document 元素不支持注入字体。
ERR_DOWNLOAD下载所提供的资源失败。
ERR_FONT_FAMILY提供了无效的字体族名称。
ERR_UNLOAD尝试卸载尚未完成加载的字体。