Fontdue provides a naïve layout API designed for simplicity. Layout operations require a Layout context, which manages heap allocations. Reusing a Layout instance via .reset() is recommended to reduce allocation overhead.
Workflow:
- Create a
Layout instance, specifying the CoordinateSystem (e.g., CoordinateSystem::PositiveYUp). - Provide a slice of
Font instances to be used during layout. - Use
.append() to add text segments using TextStyle. Each segment specifies the text string, font size, and the index of the font in your provided font list. - Access the resulting glyphs via
.glyphs().
Note: The layout API is currently immature and may undergo breaking changes.
// Read the font data.
let font = include_bytes!("../resources/fonts/Roboto-Regular.ttf") as &[u8];
// Parse it into the font type.
let roboto_regular = Font::from_bytes(font, fontdue::FontSettings::default()).unwrap();
// The list of fonts that will be used during layout.
let fonts = &[roboto_regular];
// Create a layout context. Laying out text needs some heap allocations; reusing this context
// reduces the need to reallocate space. We inform layout of which way the Y axis points here.
let mut layout = Layout::new(CoordinateSystem::PositiveYUp);
// By default, layout is initialized with the default layout settings. This call is redundant,
// but demonstrates setting the value with your custom settings.
layout.reset(&LayoutSettings {
..LayoutSettings::default()
});
// The text that will be laid out, its size, and the index of the font in the font list to use for
// that section of text.
layout.append(fonts, &TextStyle::new("Hello ", 35.0, 0));
layout.append(fonts, &TextStyle::new("world!", 40.0, 0));
// Prints the layout for "Hello world!"
println!("{:?}", layout.glyphs());