首页指南参考教程

字体

了解如何使用本地文件或 Google Font 包将自定义字体集成到应用中


Android 和 iOS 都有自己的一套平台字体。为了提供一致的用户体验并增强应用的品牌,你可以使用自定义字体。

¥Android and iOS come with their own set of platform fonts. To provide a consistent user experience and enhance your app's branding, you can use custom fonts.

本指南介绍了向项目中添加和加载自定义字体的不同方法,还提供了与字体相关的其他信息。

¥This guide covers different ways you can add and load a custom font into your project and also provides additional information related to fonts.

添加自定义字体

¥Add a custom font

有两种方法可以将自定义字体添加到项目中:

¥There are two ways you can add a custom font into your project:

  • 将字体文件添加到你的本地资源中。例如,assets/fonts 目录中的字体文件。

    ¥Add a font file into your local assets. For example, a font file in the assets/fonts directory.

  • 安装 Google 字体包。例如,安装 @expo-google-fonts/inter 包。

    ¥Install a Google Font package. For example, installing @expo-google-fonts/inter package.

支持的字体格式

¥Supported font formats

Expo SDK 正式支持 Android、iOS 和 Web 平台上的 OTF 和 TTF 字体格式。如果你的字体是其他字体格式,则必须设置高级配置以在你的项目中支持该格式。

¥Expo SDK officially supports OTF and TTF font formats across Android, iOS and web platforms. If your font is in another font format, you have to set up advanced configuration to support that format in your project.

如何在 OTF 和 TTF 之间进行选择

¥How to choose between OTF and TTF

如果你使用的字体同时具有 OTF 和 TTF 版本,则最好使用 OTF。.otf 文件比 .ttf 文件小。有时,OTF 在某些情况下也会渲染得更好一些。

¥If the font you're using have both OTF and TTF versions, prefer OTF. The .otf files are smaller than .ttf files. Sometimes, OTF also renders slightly better in certain contexts.

使用本地字体文件

¥Use a local font file

将文件复制到项目的 assets/fonts 目录中。

¥Copy the file into your project's assets/fonts directory.

assets/fonts 目录路径是 React Native 应用中放置字体文件的常见约定。如果你遵循自定义约定,你可以将这些文件放在其他地方。

在你的项目中使用本地字体文件的两种方法:

¥Two ways to use the local font file your project:

使用 expo-font 配置插件

¥With expo-font config plugin

expo-font 配置插件允许在项目的原生代码中嵌入一个或多个字体文件。此方法有几个好处:

¥The expo-font config plugin allows embedding one or more font files in your project's native code. This method has a few benefits:

  • 当应用在设备上启动时立即可用。

    ¥Available immediately when the app starts on a device.

  • 应用启动时,无需额外代码即可异步加载项目中的字体。

    ¥No additional code required to load fonts in a project asynchronously when the app starts.

  • 由于字体已打包在应用中,因此它们在安装应用的所有设备上始终可用。

    ¥Fonts are consistently available across all devices where the app is installed because they're bundled within the app.

但是,这种方法也有一些限制:

¥However, this method also has some limitations:

  • 不适用于 Expo Go,因为此方法需要 创建开发构建

    ¥Doesn't work with Expo Go since this method requires creating a development build.

  • 仅适用于 SDK 50 及以上版本。

    ¥Only available for SDK 50 and above.

要在项目中嵌入字体,请按照以下步骤操作:

¥To embed a font in a project, follow the steps below:

1

在项目中添加自定义字体文件后,安装 expo-font 库。

¥After adding a custom font file in your project, install the expo-font library.

Terminal
npx expo install expo-font

2

将配置插件添加到你的 应用配置 文件中。配置必须包含使用 fonts 属性的字体文件路径,该属性采用一个或多个字体文件的数组。每个字体文件的路径都相对于项目的根目录。例如,在以下配置中,定义了 Inter-Black.otf 字体文件的路径。

¥Add the config plugin to your app config file. The configuration must contain the path to the font file using fonts property which takes an array of one or more font files. The path to each font file is relative to the project's root. For example, in the following configuration, Inter-Black.otf font file's path is defined.

app.json
{
  "expo": {
    "plugins": [
      [
        "expo-font",
        {
          "fonts": ["./assets/fonts/Inter-Black.otf"]
        }
      ]
    ]
  }
}

3

使用配置插件嵌入字体后,创建 下一节 并将其安装在你的设备或 Android 模拟器或 iOS 模拟器上。

¥After embedding the font with the config plugin, create a new development build and install it on your device or Android Emulator or iOS Simulator.

你可以通过指定 fontFamily 样式属性将字体与 <Text> 一起使用。请参阅 获取设备令牌,了解如何确定字体系列名称。

¥You can use the font with <Text> by specifying the fontFamily style prop. See the next section on how to determine the font family name.

在下面的示例中,<Text> 使用 Inter-Black 作为字体系列名称:

¥In the example below, the <Text> uses the Inter-Black as the font family name:

<Text style={{ fontFamily: 'Inter-Black' }}>Inter Black.</Text>
Using this method in a bare React Native project?
  • 安卓:将字体文件复制到 android/app/src/main/assets/fonts。

    ¥Android: Copy font files to android/app/src/main/assets/fonts.

  • iOS:请参阅 Apple 开发者文档中的 向你的应用添加自定义字体

    ¥iOS: See Adding a Custom Font to Your App in the Apple Developer documentation.

如何确定要使用的字体系列名称

¥How to determine which font family name to use

在 Android 上,字体系列名称与字体文件的名称相同(没有扩展名)。在 iOS 上,字体系列名称是从字体文件本身读取的。

¥On Android, the font family name is the same as of the font file (without the extension). On iOS, the font family name is read from the font file itself.

我们建议将字体文件命名为与其 PostScript 名称 相同的名称,以便字体系列名称在两个平台上保持一致。

¥We recommend naming the font file same as its PostScript name so the font family name is consistent on both platforms.

What is PostScript name of a font file?

字体文件的 PostScript 名称是分配给字体的唯一标识符,遵循 Adob​​e 的 PostScript 标准。它被操作系统和应用用来引用字体。它不是字体的显示名称。

¥The PostScript name of a font file is a unique identifier assigned to the font that follows Adobe's PostScript standard. It is used by operating systems and apps to refer to the font. It is not a font's display name.

例如,Inter Black 字体文件的 PostScript 名称是 Inter-Black

¥For example, Inter Black font file's PostScript name is Inter-Black.

使用 useFonts hook

¥With useFonts hook

expo-font 库中的 useFonts 钩子允许异步加载字体文件。此钩子会跟踪加载状态并在应用初始化时加载字体。

¥The useFonts hook from expo-font library allows loading the font file asynchronously. This hook keeps track of the loading state and loads the font when an app is initialized.

它适用于所有 Expo SDK 版本和 Expo Go。要使用 useFonts 钩子在项目中加载字体,请按照以下步骤操作:

¥It works with all Expo SDK versions and with Expo Go. To load a font in a project using useFonts hook, follow the steps below:

1

在项目中添加自定义字体文件后,安装 expo-fontexpo-splash-screen 库。

¥After adding a custom font file in your project, install the expo-font and expo-splash-screen libraries.

Terminal
npx expo install expo-font expo-splash-screen

expo-splash-screen 库提供 SplashScreen 组件,你可以使用它来防止在字体加载并准备就绪之前渲染应用。

¥The expo-splash-screen library provides SplashScreen component that you can use to prevent rendering the app until the font is loaded and ready.

2

使用顶层组件(例如项目中的根布局 (app/layout.tsx) 文件)中的 useFonts 钩子映射字体文件:

¥Map the font file using the useFonts hook in a top level component such as the root layout (app/layout.tsx) file in your project:

app/_layout.tsx
import { useFonts } from 'expo-font';
import * as SplashScreen from 'expo-splash-screen';
import {useEffect} from 'react';

SplashScreen.preventAutoHideAsync();

export default function RootLayout() {
  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 (
    %%placeholder-start%%... %%placeholder-end%%
  )
}

3

通过在 React 组件中使用 fontFamily 样式属性在 <Text> 上使用字体:

¥Use the font on the <Text> by using fontFamily style prop in a React component:

<Text style={{ fontFamily: 'Inter-Black' }}>Inter Black</Text>

使用 Google 字体

¥Use Google Fonts

Expo 对 谷歌字体 中列出的所有字体都有一流的支持。它们可使用 @expo-google-fonts 库获得。使用此库中的任何字体包,你都可以快速集成该字体及其变体。

¥Expo has first-class support for all fonts listed in Google Fonts. They are available using @expo-google-fonts library. With any of the font package from this library, you can quickly integrate that font and its variants.

在你的项目中使用 Google 字体的两种方法:

¥Two ways to use a Google Font in your project:

使用 expo-font 配置插件

¥With expo-font config plugin

注意:使用 expo-font 配置插件嵌入 Google 字体与自行嵌入自定义字体具有相同的优点和局限性。请参阅 使用本地字体文件使用 expo-font 钩子 了解更多信息。

¥Note: Embedding a Google Font using expo-font config plugin has same benefits and limitations as embedding a custom font on your own. See using a local font file with expo-font config plugin for more information.

1

安装字体包。例如,要使用 Inter Black 字体,请使用以下命令安装 @expo-google-fonts/inter 包。

¥Install the font package. For example, to use Inter Black font, install the @expo-google-fonts/inter package with the command below.

Terminal
npx expo install expo-font @expo-google-fonts/inter

2

将配置插件添加到你的 应用配置 文件中。配置必须包含使用 fonts 属性的字体文件路径,该属性采用一个或多个字体文件的数组。字体文件的路径是从 node_modules 目录内的字体包中定义的。例如,如果你有一个名为 @expo-google-fonts/inter 的字体包,则文件的名称为 Inter_900Black.ttf。

¥Add the config plugin to your app config file. The configuration must contain the path to the font file using fonts property which takes an array of one or more font files. The path to the font file is defined from the font package inside the node_modules directory. For example, if you have a font package named @expo-google-fonts/inter, then the name of the file is Inter_900Black.ttf.

app.json
{
  "plugins": [
    [
      "expo-font",
      {
        "fonts": ["node_modules/@expo-google-fonts/inter/Inter_900Black.ttf"]
      }
    ]
  ]
}

3

使用配置插件嵌入字体后,创建 下一节 并将其安装在你的设备或 Android 模拟器或 iOS 模拟器上。

¥After embedding the font with the config plugin, create a new development build and install it on your device or Android Emulator or iOS Simulator.

在 Android 上,你可以使用字体文件名。例如,Inter_900Black。在 iOS 上,使用字体及其粗细名称(PostScript 名称)。下面的示例演示了如何使用 Platform 为每个平台选择正确的字体系列名称:

¥On Android, you can use the font file name. For example, Inter_900Black. On iOS, use the font and its weight name (PostScript name). The example below demonstrates how to use Platform to select the correct font family name for each platform:

import { Platform } from 'react-native';

// Inside a React component:
<Text
  style={{
    fontFamily: Platform.select({
      android: 'Inter_900Black',
      ios: 'Inter-Black',
    }),
  }}>
  Inter Black
</Text>

使用 useFonts hook

¥With useFonts hook

注意:使用 useFonts 钩子加载 Google 字体与自己嵌入自定义字体具有相同的优点和局限性。请参阅 vanilla React Native 应用 了解更多信息。

¥Note: Loading a Google Font using useFonts hook has same benefits and limitations as embedding a custom font on your own. See using a local font file with useFonts hook for more information.

每个 google Fonts 包都提供 useFonts 钩子来异步加载字体。此钩子会跟踪加载状态并在应用初始化时加载字体。字体包还会导入字体文件,因此你不必明确导入它。

¥Each google Fonts package provides the useFonts hook to load the fonts asynchronously. This hook keeps track of the loading state and loads the font when an app is initialized. The font package also imports the font file so you don't have to explicitly import it.

1

安装 Google 字体包、expo-fontexpo-splash-screen 库。

¥Install the Google Fonts package, expo-font and expo-splash-screen libraries.

Terminal
npx expo install @expo-google-fonts/inter expo-font expo-splash-screen

expo-splash-screen 库提供 SplashScreen 组件,你可以使用它来防止在字体加载并准备就绪之前渲染应用。

¥The expo-splash-screen library provides SplashScreen component that you can use to prevent rendering the app until the font is loaded and ready.

2

安装字体包后,使用顶层组件(例如项目中的根布局 (app/layout.tsx) 文件)中的 useFonts 钩子映射字体:

¥After installing the font package, map the font using the useFonts hook in a top level component such as the root layout (app/layout.tsx) file in your project:

app/_layout.tsx
// Rest of the import statements
import { Inter_900Black, useFonts } from '@expo-google-fonts/inter';
import * as SplashScreen from 'expo-splash-screen';
import {useEffect} from 'react';

SplashScreen.preventAutoHideAsync();

export default function RootLayout() {
  const [loaded, error] = useFonts({
    Inter_900Black,
  });

  useEffect(() => {
    if (loaded || error) {
      SplashScreen.hideAsync();
    }
  }, [loaded, error]);

  if (!loaded && !error) {
    return null;
  }

  return (
    %%placeholder-start%%... %%placeholder-end%%
  )
}

3

通过在 React 组件中使用 fontFamily 样式属性在 <Text> 上使用字体:

¥Use the font on the <Text> by using fontFamily style prop in a React component:

<Text style={{ fontFamily: 'Inter_900Black' }}>Inter Black</Text>

附加信息

¥Additional information

最小的例子

¥Minimal example

expo-font usage

请参阅 Expo Fonts API 参考中的使用部分,了解使用自定义字体的简单示例。

超越 OTF 和 TTF

¥Beyond OTF and TTF

如果你的字体采用 OTF 或 TTF 以外的格式,则必须使用 自定义 Metro 打包器配置以将其作为额外资源包含在内 才能使其工作。在某些情况下,渲染平台不支持的字体格式可能会导致你的应用崩溃。

¥If your font is in format other than OTF or TTF, you have to customize the Metro bundler configuration to include it as an extra asset for it to work. In some cases, rendering a font format that a platform doesn't support may cause your app to crash.

作为参考,下表提供了在每个原生平台上有效的列表格式:

¥For reference, the following table provides the list formats that work on each native platform:

格式安卓iOS 系统Web
bdf
dfont
eot
fon
otf
ps
svg
ttc
ttf
woff
woff2

平台内置字体

¥Platform built-in fonts

如果你不想通过指定 fontFamily 来使用自定义字体,则将使用平台的默认字体。每个平台都有一组内置字体。在 Android 上,默认字体是 Roboto。在 iOS 上,它是 SF Pro。

¥If you don't want to use a custom font by specifying a fontFamily, platform's default font will be used. Each platform has a set of built in fonts. On Android, the default font is Roboto. On iOS, it's SF Pro.

平台的默认字体通常易于阅读。但是,当系统默认字体更改为使用另一种不易阅读的字体时,请不要感到惊讶。在这种情况下,请使用自定义字体,以便你可以精确控制用户将看到的内容。

¥A platform's default font is usually easy-to-read. However, don't be surprised when the system default font is changed to use another font that is not easy to read. In this case, use your custom font so you have precise control over what the user will see.

处理 @expo/vector-icons 初始负载

¥Handle @expo/vector-icons initial load

@expo/vector-icons 库中的图标首次加载时,它们在你的应用中显示为不可见图标。加载后,它们将被缓存以供应用后续使用。为避免在应用首次加载时显示不可见的图标,请在初始加载屏幕期间使用 useFonts 进行预加载。例如:

¥When the icons from @expo/vector-icons library load for the first time, they appear as invisible icons in your app. Once they load, they're cached for all the app's subsequent usage. To avoid showing invisible icons on your app's first load, preload during the initial loading screen with useFonts. For example:

app/_layout.tsx
import { useFonts } from 'expo-font';
import Ionicons from '@expo/vector-icons/Ionicons';

export default function RootLayout() {
  useFonts([require('./assets/fonts/Inter-Black.otf', FontAwesome.font)]);

  return (
    %%placeholder-start%%... %%placeholder-end%%
  )
}

现在,你可以在 React 组件中使用 Ionicons 库中的任何图标:

¥Now, you can any icon from the Ionicons library in a React component:

<Ionicons name="checkmark-circle" size={32} color="green" />
图标

了解如何在 Expo 应用中使用各种类型的图标,包括矢量图标、自定义图标字体、图标图片和图标按钮。

直接从网络加载远程字体

¥Loading a remote font directly from the web

如果你正在加载远程字体,请确保它们来自正确配置 CORS 的来源。如果你不这样做,你的远程字体可能无法在 Web 平台上正确加载。

从本地资源加载字体是在应用中加载字体的最安全方法。将字体作为本地资源包含时,在将应用提交到应用商店后,这些字体将与应用下载打包在一起并立即可用。你不必担心 CORS 或其他潜在问题。

¥Loading fonts from a local asset is the safest way to load a font in your app. When including fonts as local assets, after you submit your app to the app stores, these fonts are bundled with the app download and will be available immediately. You don't have to worry about CORS or other potential issues.

但是,直接从 Web 加载字体文件是通过将 require('./assets/fonts/FontName.otf') 替换为你的字体的 URL 来完成的,如下例所示。

¥However, loading a font file directly from web is done by replacing the require('./assets/fonts/FontName.otf') with the URL of your font as shown in the example below.

Using a remote font
import { useFonts } from 'expo-font';
import { Text, View, StyleSheet } from 'react-native';

export default function App() {
  const [loaded, error] = useFonts({
    'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',
  });

  if (!loaded || !error) {
    return null;
  }

  return (
    <View style={styles.container}>
      <Text style={{ fontFamily: 'Inter-SemiBoldItalic', fontSize: 30 }}>Inter SemiBoldItalic</Text>
      <Text style={{ fontSize: 30 }}>Platform Default</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
Expo 中文网 - 粤ICP备13048890号