Skip to main content

minifb_ui/ui/
text.rs

1pub struct Text {
2    pub font: crate::ttf::Font,
3    pub text: String,
4}
5
6impl Text {
7    pub fn new(text: &str, font: crate::ttf::Font) -> Self {
8        Self {
9            font,
10            text: text.to_string()
11        }
12    }
13
14    pub fn get_width(&self, size: f32) -> usize {
15        self.get_width_precise(size).ceil() as usize
16    }
17
18    /// Returns the precise rendered width using the layout engine
19    pub fn get_width_precise(&self, size: f32) -> f32 {
20        use fontdue::layout::{CoordinateSystem, Layout, LayoutSettings, TextStyle};
21
22        if self.text.is_empty() {
23            return 0.0;
24        }
25
26        let fonts = self.font.as_slice();
27        let mut layout = Layout::new(CoordinateSystem::PositiveYDown);
28        layout.reset(&LayoutSettings {
29            x: 0.0,
30            y: 0.0,
31            ..Default::default()
32        });
33        layout.append(&fonts, &TextStyle::new(&self.text, size, 0));
34
35        let glyphs = layout.glyphs();
36        if let Some(last) = glyphs.last() {
37            // Use the last glyph's bitmap width for visual extent,
38            // not advance_width which includes trailing space
39            let (metrics, _) = self.font.font.rasterize_config(last.key);
40            last.x + metrics.width as f32
41        } else {
42            0.0
43        }
44    }
45}