Skip to main content

firefly_rust/graphics/
font.rs

1use crate::*;
2
3/// A loaded font file.
4///
5/// Can be loaded as [`FileBuf`] from ROM with [`load_file_buf`]
6/// and then cast using [`FileBuf::as_font`].
7pub struct Font<'a> {
8    pub(crate) raw: &'a [u8],
9}
10
11impl Font<'_> {
12    /// Check if the font encoding is ASCII.
13    #[must_use]
14    pub fn is_ascii(&self) -> bool {
15        self.raw[1] == 0
16    }
17
18    /// Calculate width (in pixels) of the given ASCII text.
19    ///
20    /// This function does not account for newlines.
21    #[must_use]
22    pub fn line_width_ascii(&self, t: &str) -> u32 {
23        t.len() as u32 * u32::from(self.char_width())
24    }
25
26    /// Calculate width (in pixels) of the given UTF-8 text.
27    ///
28    /// This function does not account for newlines.
29    #[must_use]
30    pub fn line_width_utf8(&self, t: &str) -> u32 {
31        t.chars().count() as u32 * u32::from(self.char_width())
32    }
33
34    /// The width (in pixels) of one glyph bounding box.
35    #[must_use]
36    pub fn char_width(&self) -> u8 {
37        self.raw[2]
38    }
39
40    /// The height (in pixels) of one glyph (one line) bounding box.
41    #[must_use]
42    pub fn char_height(&self) -> u8 {
43        self.raw[3]
44    }
45
46    /// Offset from the top of the glyph bounding box to the baseline.
47    #[must_use]
48    pub fn baseline(&self) -> u8 {
49        self.raw[4]
50    }
51}
52
53impl<'a> From<File<'a>> for Font<'a> {
54    fn from(value: File<'a>) -> Self {
55        Self { raw: value.raw }
56    }
57}
58
59#[cfg(feature = "alloc")]
60impl<'a> From<&'a FileBuf> for Font<'a> {
61    fn from(value: &'a FileBuf) -> Self {
62        Self { raw: &value.raw }
63    }
64}