To use COSMIC Text, follow this general workflow:
- Create a
FontSystem to access system fonts (create one per application). - Create a
SwashCache to store rasterized glyphs (create one per application). - Define
Metrics for font size and line height. - Create a
Buffer using the FontSystem and Metrics (create one per text widget). - Use
Attrs to specify font choices. - Set the buffer size and text using
set_size and set_text. - Inspect the layout via
layout_runs() or draw the buffer using draw().
Note: For high-performance rendering, it is recommended to use SwashCache directly rather than the buffer.draw() convenience method.
use cosmic_text::{Attrs, Color, FontSystem, SwashCache, Buffer, Metrics, Shaping};
// A FontSystem provides access to detected system fonts, create one per application
let mut font_system = FontSystem::new();
// A SwashCache stores rasterized glyphs, create one per application
let mut swash_cache = SwashCache::new();
// Text metrics indicate the font size and line height of a buffer
let metrics = Metrics::new(14.0, 20.0);
// A Buffer provides shaping and layout for a UTF-8 string, create one per text widget
let mut buffer = Buffer::new(&mut font_system, metrics);
// Borrow buffer together with the font system for more convenient method calls
let mut buffer = buffer.borrow_with(&mut font_system);
// Attributes indicate what font to choose
let attrs = Attrs::new();
// Set size and text
buffer.set_size(Some(80.0), Some(25.0));
buffer.set_text("Hello, Rust! 🦀\n", &attrs, Shaping::Advanced, None);
// Inspect the output runs
for run in buffer.layout_runs() {
for glyph in run.glyphs.iter() {
println!("{:#?}", glyph);
}
}
// Create a default text color
let text_color = Color::rgb(0xFF, 0xFF, 0xFF);
// Draw the buffer (for performance, instead use SwashCache directly)
buffer.draw(&mut swash_cache, text_color, |x, y, w, h, color| {
// Fill in your code here for drawing rectangles
});