Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

使用字体

Godot 中能够为不同的 UI 节点设置指定的字体。

There are three different places where you can setup font usage. The first is the theme editor. Choose the node you want to set the font for and select the font tab. The second is in the inspector for control nodes under Theme Overrides > Fonts. Lastly, in the inspector settings for themes under Default Font.

If no font override is specified anywhere, Open Sans SemiBold is used as the default project font.

备注

Since Godot 4.0, font sizes are no longer defined in the font itself but are instead defined in the node that uses the font. This is done in the Theme Overrides > Font Sizes section of the inspector.

This allows changing the font size without having to duplicate the font resource for every different font size.

There are 2 kinds of font files: dynamic (TTF/OTF/WOFF/WOFF2 formats) and bitmap (BMFont .fnt format or monospaced image). Dynamic fonts are the most commonly used option, as they can be resized and still look crisp at higher sizes. Thanks to their vector-based nature, they can also contain a lot more glyphs while keeping a reasonable file size compared to bitmap fonts. Dynamic fonts also support some advanced features that bitmap fonts cannot support, such as ligatures (several characters transforming into a single different design).

小技巧

You can find freely licensed font files on websites such as Google Fonts and Font Library.

Fonts are covered by copyright. Double-check the license of a font before using it, as not all fonts allow commercial use without purchasing a license.

参见

You can see how fonts work in action using the BiDI and Font Features demo project.

动态字体

Godot 支持以下动态字体格式:

  • TrueType 字体或合集(.ttf.ttc

  • OpenType 字体或合集(.otf.otc

  • Web 开放字体格式 1(.woff

  • Web 开放字体格式 2(.woff2,从 Godot 3.5 开始支持)

While .woff and especially .woff2 tend to result in smaller file sizes, there is no universally "better" font format. In most situations, it's recommended to use the font format that was shipped on the font developer's website.

位图字体

Godot supports the BMFont (.fnt) bitmap font format. This is a format created by the BMFont program. Many BMFont-compatible programs also exist, like BMGlyph.

Alternatively, you can import any image to be used as a bitmap font. This is only supported for monospaced fonts (fonts where each character has the same width). To do so, select the image in the FileSystem dock, go to the Import dock, change its import type to Font Data (Monospace Image Font) then click Reimport:

将导入类型修改为 Font Data (Monospace Image Font)

将导入类型修改为 Font Data (Monospace Image Font)

字体可以使用任意顺序的字符集布局,但建议使用与标准 Unicode 一致的顺序,这样导入所需的配置就会少很多。例如,下面的位图字体包含了 ASCII 字符,与标准 ASCII 顺序一致:

位图字体示例

Credit: LibreQuake (scaled and cropped to exclude extended range)

The following import options can be used to import the above font image successfully:

上面的示例字体使用的导入选项

上面的示例字体使用的导入选项

The Character Ranges option is an array that maps each position on the image (in tile coordinates, not pixels). The font atlas is traversed from left to right and top to bottom. Characters can be specified with decimal numbers (127), hexadecimal numbers (0x007f) or between single quotes ('~'). Ranges can be specified with a hyphen between characters.

For instance, 0-127 (or 0x0000-0x007f) denotes the full ASCII range. As another example, ' '-'~' is equivalent to 32-127 and denotes the range of printable (visible) ASCII characters.

Make sure the Character Ranges option doesn't exceed the number of Columns × Rows defined. Otherwise, the font will fail to import.

If your font image contains margins not used for font glyphs (such as attribution information), try adjusting Image Margin. This is a margin applied only once around the whole image.

If your font image contains guides (in the form of lines between glyphs) or if spacing between characters appears incorrect, try adjusting Character Margin. This margin is applied for every imported glyph.

加载字体文件

To load a font file (dynamic or bitmap), use the resource dropdown's Quick Load or Load option next to a font property, then navigate to the font file in question:

../../_images/using_fonts_load_font.webp

加载字体文件

You can also drag-and-drop a font file from the FileSystem dock to the inspector property that accepts a Font resource.

警告

In Godot 4.0 and later, texture filter and repeat properties are defined in the location where the texture is used, rather than on the texture itself. This also applies to fonts (both dynamic fonts and bitmap fonts).

Fonts that have a pixel art appearance should have bilinear filtering disabled by changing the Rendering > Textures > Canvas Textures > Default Texture Filter project setting to Nearest.

The font size must also be an integer multiple of the design size (which varies on a per-font basis), and the Control node using the font must be scaled by an integer multiple as well. Otherwise, the font may look blurry. Font sizes in Godot are specified in pixels (px), not points (pt). Keep this in mind when comparing font sizes across different software.

The texture filter mode can also be set on individual nodes that inherit from CanvasItem by setting CanvasItem.texture_filter.

字体轮廓与阴影

Font outlines and shadows can be used to improve readability when the background color isn't known in advance. For instance, this is the case for HUD elements that are drawn over a 2D/3D scene.

Font outlines are available in most nodes that derive from Control, in addition to Label3D.

To enable outline for a font on a given node, configure the theme overrides Font Outline Color and Outline Size in the inspector. The result should look like this:

字体轮廓示例

字体轮廓示例

备注

If using a font with MSDF rendering, its MSDF Pixel Range import option be set to at least twice the value of the outline size for outline rendering to look correct. Otherwise, the outline may appear to be cut off earlier than intended.

Support for font shadows is more limited: they are only available in Label and RichTextLabel. Additionally, font shadows always have a hard edge (but you can reduce their opacity to make them look more subtle). To enable font shadows on a given node, configure the Font Shadow Color, Shadow Offset X, and Shadow Offset Y theme overrides in a Label or RichTextLabel node accordingly:

Configuring font shadow in a Label node

Configuring font shadow in a Label node

The result should look like this:

字体阴影示例

字体阴影示例

小技巧

You can create local overrides to font display in Label nodes by creating a LabelSettings resource that you reuse across Label nodes. This resource takes priority over theme properties.

高级字体特性

抗锯齿

You can adjust how the font should be smoothed out when rendering by adjusting antialiasing and hinting. These are different properties, with different use cases.

Antialiasing controls how glyph edges should be smoothed out when rasterizing the font. The default antialiasing method (Grayscale) works well on every display technology. However, at small sizes, grayscale antialiasing may result in fonts looking blurry.

The antialiasing sharpness can be improved by using LCD subpixel optimization, which exploits the subpixel patterns of most LCD displays by offsetting the font antialiasing on a per-channel basis (red/green/blue). The downside is that this can introduce "fringing" on edges, especially on display technologies that don't use standard RGB subpixels (such as OLED displays).

In most games, it's recommended to stick to the default Grayscale antialiasing. For non-game applications, LCD subpixel optimization is worth exploring.

字体抗锯齿对比

From top to bottom: Disabled, Grayscale, LCD Subpixel (RGB)

备注

MSDF 渲染的字体无法修改抗锯齿——这种字体始终使用灰度抗锯齿进行渲染。

微调

微调控制的是对字体进行栅格化的时候,字形边缘吸附到像素的程度。None看上去最平滑,字体较小时会看上去比较模糊。Light(默认值)只会在 Y 轴上对字形的边缘进行吸附,看上去会比较锐利,而 Full 则更加锐利,X 轴和 Y 轴都会进行边缘的吸附。对微调模式的选择取决于你个人的口味。

字体微调对比

From top to bottom: None, Light, Full hinting

备注

If changing the hinting mode has no visible effect after clicking Reimport, it's usually because the font doesn't include hinting instructions. This can be resolved by looking for a version of the font file that includes hinting instructions, or enabling Force Autohinter in the Import dock. This will use FreeType's autohinter to automatically add hinting instructions to the imported font.

次像素定位

Subpixel positioning can be adjusted. This is a FreeType feature that allows glyphs to be rendered more closely to their intended form. The default setting of Auto automatically enables subpixel positioning at small sizes, but disables it at large font sizes to improve rasterization performance.

You can force the subpixel positioning mode to Disabled, One half of a pixel or One quarter of a pixel. One quarter of a pixel provides the best quality, at the cost of longer rasterization times.

Changing antialiasing, hinting and subpixel positioning has the most visible effect at smaller font sizes.

警告

Fonts that have a pixel art appearance should have their subpixel positioning mode set to Disabled. Otherwise, the font may appear to have uneven pixel sizes.

This step is not required for bitmap fonts, as subpixel positioning is only relevant for dynamic fonts (which are usually made of vector elements).

Mipmap

默认情况下字体不会生成 Mipmap,这样就能够降低内存占用、加速栅格化。但这样一来,缩小后的字体就会变成一坨。3D 文本 不启用 Fixed Size 的时候尤为明显。如果在 Control 节点中使用传统的栅格化字体(非 MSDF 字体)显示文本,并且该节点的缩放比 (1, 1) 要小,也会出现这种情况。

在“文件系统”面板中选中字体后,你可以在“导入”面板中启用 Mipmap,从而改善字体缩小渲染后的外观。

MSDF 字体也可以启用 Mipmap。在字体大小小于默认值时,这可以稍稍改善字体的渲染质量,但 MSDF 字体在放大后原本就是没有颗粒度问题的。

MSDF 字体渲染

多通道带符号距离场(Multi-channel signed distance field,MSDF)字体渲染能够将字体渲染为任意大小,无需在大小发生变化时重新栅格化。

与 Godot 默认使用的传统字体栅格化相比,MSDF 字体渲染有两个优点:

  • 即便文字非常巨大,字体看上去也总是清晰的。

  • 首次渲染大字号字体的字符时卡顿更短,因为无须执行栅格化。

MSDF 字体渲染的缺点有:

  • 字体渲染的基础开销较高。桌面平台上通常无法察觉,但是会影响低端移动设备。

  • 由于缺少微调,较小的字体没有栅格化字体清晰。

  • 与传统的栅格化字体相比,首次为新字形渲染小字号字体的开销可能更大。可以使用 字体预渲染 缓解。

  • 无法为 MSDF 字体启用 LCD 次像素优化。

  • MSDF 模式下无法正确渲染轮廓自相交的字体。如果使用从 Google Fonts 等处下载到的字体时出现渲染问题,请尝试改为从作者的官方网站下载。

Comparison of font rasterization methods

Comparison of font rasterization methods. From top to bottom: rasterized without oversampling, rasterized with oversampling, MSDF

To enable MSDF rendering for a given font, select it in the FileSystem dock, go to the Import dock, enable Multichannel Signed Distance Field, then click Reimport:

Enabling MSDF in the font's import options

Enabling MSDF in the font's import options

使用 Emoji

Godot 对 Emoji 字体的支持有限:

  • 支持 CBDT/CBLC(内嵌 PNG)和 SVG Emoji 字体。

  • 不支持 COLR/CPAL Emoji 字体(自定义矢量格式)。

  • 不支持 EMJC 位图压缩(iOS 系统 Emoji 字体需要用到)。这意味着如果要在 iOS 上支持 Emoji,你就必须改用自定义的使用 SVG 或 PNG 位图压缩的字体。

For Godot to be able to display emoji, the font used (or one of its fallbacks) needs to include them. Otherwise, emoji won't be displayed and placeholder "tofu" characters will appear instead:

尝试在标签中使用 Emoji 的默认外观

尝试在标签中使用 Emoji 的默认外观

After adding a font to display emoji such as Noto Color Emoji, you get the expected result:

为标签添加 Emoji 字体后的正确外观

为标签添加 Emoji 字体后的正确外观

To use a regular font alongside emoji, it's recommended to specify a fallback font that points to the emoji font in the regular font's advanced import options. If you wish to use the default project font while displaying emoji, leave the Base Font property in FontVariation empty while adding a font fallback pointing to the emoji font:

小技巧

Emoji fonts are quite large in size, so you may want to load a system font to provide emoji glyphs rather than bundling it with your project. This allows providing full emoji support in your project without increasing the size of its exported PCK. The downside is that emoji will look different depending on the platform, and loading system fonts is not supported on all platforms.

也可以将系统字体用作回退字体。

使用图标字体

Tools like Fontello can be used to generate font files containing vectors imported from SVG files. This can be used to render custom vector elements as part of your text, or to create extruded 3D icons with 3D 文本 and TextMesh.

备注

Fontello currently does not support creating multicolored fonts (which Godot can render). As of November 2022, support for multicolored fonts in icon font generation tools remains scarce.

Depending on your use cases, this may lead to better results compared to using the img tag in RichTextLabel. Unlike bitmap images (including SVGs which are rasterized on import by Godot), true vector data can be resized to any size without losing quality.

After downloading the generated font file, load it in your Godot project then specify it as a custom font for a Label, RichTextLabel or Label3D node. Switch over to the Fontello web interface, then copy the character by selecting it then pressing Ctrl + C (Cmd + C on macOS). Paste the character in the Text property of your Label node. The character will appear as a placeholder glyph in the inspector, but it should appear correctly in the 2D/3D viewport.

To use an icon font alongside a traditional font in the same Control, you can specify the icon font as a fallback. This works because icon fonts use the Unicode private use area, which is reserved for use by custom fonts and doesn't contain standard glyphs by design.

备注

Several modern icon fonts such as Font Awesome 6 have a desktop variant that uses ligatures to specify icons. This allows you to specify icons by entering their name directly in the Text property of any node that can display fonts. Once the icon's name is fully entered as text (such as house), it will be replaced by the icon.

While easier to use, this approach cannot be used with font fallbacks as the main font's characters will take priority over the fallback font's ligatures.

字体回退

Godot supports defining one or more fallbacks when the main font lacks a glyph to be displayed. There are 2 main use cases for defining font fallbacks:

  • Use a font that only supports Latin character sets, but use another font to be able to display text another character set such as Cyrillic.

  • Use a font to render text, and another font to render emoji or icons.

Open the Advanced Import Settings dialog by double-clicking the font file in the FileSystem dock. You can also select the font in the FileSystem dock, go to the Import dock then choose Advanced… at the bottom:

../../_images/using_fonts_advanced_import_settings.webp

导入面板

In the dialog that appears, look for Fallbacks section on the sidebar on the right, click the Array[Font] (size 0) text to expand the property, then click Add Element:

../../_images/using_fonts_font_fallbacks_add.webp

添加字体回退

Click the dropdown arrow on the new element, then choose a font file using the Quick Load or Load options:

../../_images/using_fonts_font_fallbacks_load.webp

加载字体回退

It is possible to add fallback fonts while using the default project font. To do so, leave the Base Font property empty while adding one or more font fallbacks.

备注

Font fallbacks can also be defined on a local basis similar to OpenType 字体特性, but this is not covered here for brevity reasons.

可变字体

Godot has full support for variable fonts, which allow you to use a single font file to represent various font weights and styles (regular, bold, italic, …). This must be supported by the font file you're using.

To use a variable font, create a FontVariation resource in the location where you intend to use the font, then load a font file within the FontVariation resource:

../../_images/using_fonts_font_variation_create.webp

创建 FontVariation 资源

../../_images/using_fonts_font_variation_load.webp

为 FontVariation 资源加载字体文件

Scroll down to the FontVariation's Variation section, then click the Variation Coordinates text to expand the list of axes that can be adjusted:

../../_images/using_fonts_font_variation_variable_font.webp

可变轴列表

The set of axes you can adjust depends on the font loaded. Some variable fonts only support one axis of adjustment (typically weight or slant), while others may support multiple axes of adjustment.

For example, here's the Inter V font with a weight of 900 and a slant of -10:

../../_images/using_fonts_font_variation_variable_font_example.webp

可变字体示例(Inter V)

小技巧

While variable font axis names and scales aren't standardized, some common conventions are usually followed by font designers. For instance, the weight axis typically uses 400 as the "regular" font weight and 700 as the "bold" font weight.

You can save the FontVariation to a .tres resource file to reuse it in other places:

../../_images/using_fonts_font_variation_save_to_file.webp

将 FontVariation 保存为外部资源文件

假粗体和假斜体

When writing text in bold or italic, using font variants specifically designed for this looks better. Spacing between glyphs will be more consistent when using a bold font, and certain glyphs' shapes may change entirely in italic variants (compare "a" and "a").

However, real bold and italic fonts require shipping more font files, which increases distribution size. A single variable font file can also be used, but this file will be larger than a single non-variable font. While file size is usually not an issue for desktop projects, it can be a concern for mobile/web projects that strive to keep distribution size as low as possible.

To allow bold and italic fonts to be displayed without having to ship additional fonts (or use a variable font that is larger in size), Godot supports faux bold and italic.

Faux bold/italic (top), real bold/italic (bottom). Normal font used: Open Sans SemiBold

Faux bold/italic (top), real bold/italic (bottom). Normal font used: Open Sans SemiBold

Faux bold and italic is automatically used in RichTextLabel's bold and italic tags if no custom fonts are provided for bold and/or italic.

To use faux bold, create a FontVariation resource in a property where a Font resource is expected. Set Variation > Embolden to a positive value to make a font bolder, or to a negative value to make it less bold. Recommended values are between 0.5 and 1.2 depending on the font.

Faux italic is created by skewing the text, which is done by modifying the per-character transform. This is also provided in FontVariation using the Variation > Transform property. Setting the yx component of the character transform to a positive value will italicize the text. Recommended values are between 0.2 and 0.4 depending on the font.

调整字体间距

For stylistic purposes or for better readability, you may want to adjust how a font is presented in Godot.

Create a FontVariation resource in a property where a Font resource is expected. There are 4 properties available in the Variation > Extra Spacing section, which accept positive and negative values:

  • Glyph: Additional spacing between every glyph.

  • Space: Additional spacing between words.

  • Top: Additional spacing above glyphs. This is used for multiline text, but also to calculate the minimum size of controls such as Label and Button.

  • Top: Additional spacing below glyphs. This is used for multiline text, but also to calculate the minimum size of controls such as Label and Button.

The Variation > Transform property can also be adjusted to stretch characters horizontally or vertically. This is specifically done by adjusting the xx (horizontal scale) and yy (vertical scale) components. Remember to adjust glyph spacing to account for any changes, as glyph transform doesn't affect how much space each glyph takes in the text. Non-uniform scaling of this kind should be used sparingly, as fonts are generally not designed to be displayed with stretching.

OpenType 字体特性

Godot supports enabling OpenType font features, which are a standardized way to define alternate characters that can be toggled without having to swap font files entirely. Despite being named OpenType font features, these are also supported in TrueType (.ttf) and WOFF/WOFF2 font files.

Support for OpenType features highly depends on the font used. Some fonts don't support any OpenType features, while other fonts can support dozens of toggleable features.

There are 2 ways to use OpenType font features:

Globally on a font file

Open the Advanced Import Settings dialog by double-clicking the font file in the FileSystem dock. You can also select the font in the FileSystem dock, go to the Import dock then choose Advanced… at the bottom:

../../_images/using_fonts_advanced_import_settings.webp

导入面板

In the dialog that appears, look for the Metadata Overrides > OpenType Features section on the sidebar on the right, click the Features (0 of N set) text to expand the property, then click Add Feature:

../../_images/using_fonts_advanced_import_settings_opentype_features.webp

高级导入设置中的 OpenType 特性覆盖

In a specific font usage (FontVariation)

To use a font feature, create a FontVariation resource like you would do for a variable font, then load a font file within the FontVariation resource:

../../_images/using_fonts_font_variation_create.webp

创建 FontVariation 资源

../../_images/using_fonts_font_variation_load.webp

在 FontVariation 资源中加载字体文件

Scroll down to the FontVariation's OpenType Features section, click the Features (0 of N set) text to expand the property, then click Add Feature and select the desired feature in the dropdown:

../../_images/using_fonts_font_variation_opentype_features.webp

在 FontVariation 资源中指定 OpenType 特性

For example, here's the Inter font without the Slashed Zero feature (top), then with the Slashed Zero OpenType feature enabled (bottom):

../../_images/using_fonts_font_variation_slashed_zero.webp

OpenType 特性比较(Inter)

You can disable ligatures and/or kerning for a specific font by adding OpenType features, then unchecking them in the inspector:

../../_images/using_fonts_font_variation_disable_ligatures.webp