embedded_ui/
font.rs

1use embedded_graphics::mono_font::{ascii::FONT_4X6, MonoFont};
2
3use crate::size::Size;
4
5#[derive(Clone, Copy)]
6pub enum Font {
7    Mono(&'static MonoFont<'static>),
8}
9
10impl Default for Font {
11    fn default() -> Self {
12        Self::Mono(&FONT_4X6)
13    }
14}
15
16impl Font {
17    pub fn char_size(&self) -> Size {
18        match self {
19            Font::Mono(mono) => mono.character_size.into(),
20        }
21    }
22
23    // TODO: Add text wrap strategy, also consider next line
24    pub fn measure_text_size(&self, text: &str) -> Size {
25        match self {
26            Font::Mono(mono) => {
27                let char_size = mono.character_size;
28                let char_space = mono.character_spacing;
29
30                // TODO: Optimize with single loop over chars
31                let max_line = text.split("\n").map(|s| s.len()).max().unwrap_or(0) as u32;
32                let lines_count = text.split("\n").count() as u32;
33
34                // Dividing something linear N times, gives us N + 1 parts
35                Size::new(
36                    max_line * char_size.width + (max_line - 1) * char_space,
37                    lines_count * char_size.height,
38                )
39            },
40        }
41    }
42}