Text and fonts
raylib bundles a default bitmap font that is available as soon as the window is open.
Custom fonts are loaded via RaylibHandle::load_font (from a file) or
RaylibHandle::load_font_ex (with an explicit codepoint set for preloaded glyph
atlases). Both return a RAII Font that is automatically unloaded on drop.
Text drawing — including measuring — hangs off RaylibHandle for the default font
and off the Font struct or RaylibDraw trait for custom fonts.
API surface
RaylibHandle::load_font— load a font from a file; returnsResult<Font, …>.RaylibHandle::load_font_ex— load a font with explicit font size and a codepoint array; useful for preloading a specific non-ASCII character set.RaylibHandle::measure_text— measure the pixel width of a string at a given size using the default font.Font::measure_text— measure a string with a custom font, returning aVector2(width × height).RaylibDraw::draw_text— draw a&strusing the default font.RaylibDraw::draw_text_ex— draw a&strusing a customFont, with position, size, spacing, and tint.
Example
Drawing text requires an open window. The example below opens a 640×480 window, draws a greeting with the default font each frame, and measures its width for centering.
extern crate raylib;
use raylib::prelude::*;
fn main() {
let (mut rl, thread) = raylib::init()
.size(640, 480)
.title("Text demo")
.vsync()
.build();
let message = "Hello, raylib-rs!";
let font_size = 24;
while !rl.window_should_close() {
// Measure text width for the default font.
let width = rl.measure_text(message, font_size);
let mut d = rl.begin_drawing(&thread);
d.clear_background(Color::RAYWHITE);
// Centered draw using the default font.
d.draw_text(
message,
(640 - width) / 2,
(480 - font_size) / 2,
font_size,
Color::DARKGRAY,
);
}
}
Gotchas
- Custom fonts need a window.
load_fontandload_font_excall into raylib’s GPU atlas-building path, so they must be called afterraylib::init().build(). Font data files (.ttf,.otf,.fnt,.bdf) must be on disk at the given path. - Codepoint preloading.
load_font_extakes an optional&[i32]codepoint list. IfNone, raylib loads the default Latin set (32–127). Pass an explicit list if your application draws CJK, emoji, or other extended Unicode ranges. - raylib 6.0 new text symbols. The 6.0 release added more than 30 new text utility
functions in the C library. The Rust parity checklist (
docs/superpowers/plans/) tracks which are exposed; check thetextmodule rustdoc for the current set.
See also
- Window and drawing — the draw handle that text methods live on.
Fontdocs.rs — full rustdoc for custom font operations.
Showcase examples
Showcase examples that exercise this module: