lotus_script/
font.rs

1use lotus_script_sys::FfiObject;
2use lotus_shared::content::ContentId;
3pub use lotus_shared::font::*;
4
5/// A bitmap font that can be used to render text.
6pub struct BitmapFont {
7    content_id: ContentId,
8    properties: BitmapFontProperties,
9}
10
11impl BitmapFont {
12    /// Try to load a bitmap font from a content id.
13    /// Returns `None` if the font is not currently loaded. It will be loaded in the background.
14    /// Just call this function again later until it returns `Some`.
15    pub fn try_load(content_id: ContentId) -> Option<Self> {
16        let font = FfiObject::new(&content_id);
17        let properties = unsafe { lotus_script_sys::font::bitmap_font_properties(font.packed()) };
18
19        if properties == 0 {
20            None
21        } else {
22            let properties = FfiObject::from_packed(properties).deserialize();
23            Some(Self {
24                content_id,
25                properties,
26            })
27        }
28    }
29
30    /// Get the properties of this font.
31    pub fn properties(&self) -> &BitmapFontProperties {
32        &self.properties
33    }
34
35    /// Get the width of the text in pixels.
36    pub fn text_len(&self, text: &str, letter_spacing: i32) -> u32 {
37        let font = FfiObject::new(&self.content_id);
38        let text = FfiObject::new(&text);
39
40        let len = unsafe {
41            lotus_script_sys::font::text_len(font.packed(), text.packed(), letter_spacing)
42        };
43
44        assert!(len >= 0);
45
46        len as u32
47    }
48}