aboutsummaryrefslogtreecommitdiff
path: root/src/utils.rs
blob: e36a8cc132c264c920df6560d7f4ea57877e5f64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use crate::consts::FONT_PATH;
use sdl2::{pixels::Color, render::Canvas, ttf::Sdl2TtfContext, video::Window};

#[macro_export]
macro_rules! rect(
    ($x:expr, $y:expr, $w:expr, $h:expr) => (
        ::sdl2::rect::Rect::new($x as i32, $y as i32, $w as u32, $h as u32)
    )
);

pub fn draw_text<S: AsRef<str>>(
    canvas: &mut Canvas<Window>,
    ttf_context: &Sdl2TtfContext,
    text: S,
    color: Color,
    (x, y): (u32, u32),
) {
    let text = text.as_ref();
    let texture_creator = canvas.texture_creator();
    let mut font = ttf_context.load_font(FONT_PATH, 17).unwrap();
    font.set_style(sdl2::ttf::FontStyle::NORMAL);
    font.set_hinting(sdl2::ttf::Hinting::Mono);
    let surface = font.render(text.as_ref()).blended(color).unwrap();
    let texture = texture_creator
        .create_texture_from_surface(&surface)
        .unwrap();
    let (width, height) = font.size_of_latin1(text.as_bytes()).unwrap();
    let area = rect!(x, y, width, height);
    canvas.copy(&texture, None, area).unwrap();
}