index : snake-rs
An implementation of the classic Snake game in Rust using SDL2
about summary refs log tree commit diff
snake-rs / src / ui / text.rs
-rw-r--r-- blob 39332b965ee3119f3bababd8060240f5ef71079a 1078 bytes (plain)
1
use sdl2::{pixels::Color, rect::Rect, render::Canvas, ttf, video::Window};
2
3
use crate::game_context::Point;
4
5
pub struct Text {
6
    pub text: String,
7
    pub color: Color,
8
    pub point: Point,
9
}
10
11
impl Text {
12
    pub fn new(text: &str, color: Color, point: Point) -> Self {
13
        Self {
14
            text: text.to_string(),
15
            color,
16
            point,
17
        }
18
    }
19
20
    pub fn draw(
21
        &mut self,
22
        canvas: &mut Canvas<Window>,
23
        font: &ttf::Font<'static, 'static>,
24
    ) -> Result<(), String> {
25
        let surface = font
26
            .render(&self.text)
27
            .blended(self.color)
28
            .map_err(|e| e.to_string())?;
29
30
        let texture_creator = canvas.texture_creator();
31
        let texture = texture_creator
32
            .create_texture_from_surface(&surface)
33
            .map_err(|e| e.to_string())?;
34
35
        let target = Rect::new(
36
            self.point.0,
37
            self.point.1,
38
            surface.width(),
39
            surface.height(),
40
        );
41
        canvas.copy(&texture, None, Some(target))?;
42
        Ok(())
43
    }
44
}