fontdue_sdl2/
public_api.rs

1use crate::RectAllocator;
2use fontdue::layout::GlyphPosition;
3use fontdue::Font;
4use sdl2::pixels::Color;
5use sdl2::render::{Canvas, RenderTarget, Texture, TextureCreator};
6
7/// A text-rendering-enabled wrapper for [`Texture`].
8pub struct FontTexture<'r> {
9    /// The texture containing rendered glyphs in a tightly packed
10    /// manner.
11    pub texture: Texture<'r>,
12    rect_allocator: RectAllocator,
13}
14
15impl FontTexture<'_> {
16    /// Creates a new [`FontTexture`] for rendering text.
17    ///
18    /// Consider the lifetimes of this structure and the given
19    /// [`TextureCreator`] as you would a [`Texture`] created with
20    /// one, that is why this structure is named "FontTexture".
21    ///
22    /// # Important note
23    ///
24    /// Only use a single `&[Font]` for each [`FontTexture`]. Glyphs
25    /// with the same index but different font are hard to
26    /// differentiate, so using different sets of Fonts when rendering
27    /// with a single FontTexture will lead to wrong results.
28    ///
29    /// # Errors
30    ///
31    /// The function will return an error if the Texture can't be
32    /// created, and the Err(String) will contain an error string from
33    /// SDL.
34    pub fn new<T>(texture_creator: &TextureCreator<T>) -> Result<FontTexture, String> {
35        let texture = crate::create_font_texture(texture_creator)?;
36        let rect_allocator = RectAllocator::new(1024, 1024);
37        Ok(FontTexture {
38            texture,
39            rect_allocator,
40        })
41    }
42
43    /// Renders text to the given canvas, using the given fonts and
44    /// glyphs.
45    ///
46    /// The canvas should be the same one that the [`TextureCreator`]
47    /// used in [`FontTexture::new`] was created from.
48    ///
49    /// The font-slice should be the same one that is passed to
50    /// [`Layout::append`](fontdue::layout::Layout::append).
51    ///
52    /// The glyphs should be from
53    /// [`Layout::glyphs`](fontdue::layout::Layout::glyphs).
54    ///
55    /// # Errors
56    ///
57    /// This function will return an error if the Texture cannot be
58    /// written to, or a copy from the texture to the canvas
59    /// fails. This should only really happen under very exceptional
60    /// circumstances, so text rendering is interrupted by these
61    /// errors. The Err(String) will contain an informational string
62    /// from SDL.
63    pub fn draw_text<RT: RenderTarget>(
64        &mut self,
65        canvas: &mut Canvas<RT>,
66        fonts: &[Font],
67        glyphs: &[GlyphPosition<Color>],
68    ) -> Result<(), String> {
69        crate::draw_text(
70            &mut self.texture,
71            &mut self.rect_allocator,
72            canvas,
73            fonts,
74            glyphs,
75        )
76    }
77}