fll_rs/graphics/
display.rs

1use image::{Rgb, RgbImage};
2use imageproc::rect::Rect;
3use rusttype::{Font, Scale};
4use std::rc::Rc;
5
6pub const WHITE: Rgb<u8> = Rgb([255, 255, 255]);
7pub const BLACK: Rgb<u8> = Rgb([0, 0, 0]);
8
9/// Repersents a phyical screen that can display static images
10pub trait Display {
11    fn get_image(&self) -> &RgbImage;
12    fn get_image_mut(&mut self) -> &mut RgbImage;
13
14    fn update(&mut self);
15}
16
17/// Simple graphics api that allows drawing text and rectangles
18pub struct Renderer<D> {
19    handler: D,
20    font: Rc<Font<'static>>,
21}
22
23impl<D: Display> Renderer<D> {
24    pub fn new(handler: D) -> Self {
25        let font = Rc::new(Font::try_from_bytes(include_bytes!("font.ttf")).unwrap());
26
27        Self { handler, font }
28    }
29
30    pub fn draw_rectangle_solid(
31        &mut self,
32        x: i32,
33        y: i32,
34        width: u32,
35        height: u32,
36        color: Rgb<u8>,
37    ) {
38        imageproc::drawing::draw_filled_rect_mut(
39            self.get_image_mut(),
40            Rect::at(x, y).of_size(width, height),
41            color,
42        );
43    }
44
45    pub fn draw_rectangle_hollow(
46        &mut self,
47        x: i32,
48        y: i32,
49        width: u32,
50        height: u32,
51        color: Rgb<u8>,
52    ) {
53        imageproc::drawing::draw_hollow_rect_mut(
54            self.get_image_mut(),
55            Rect::at(x, y).of_size(width, height),
56            color,
57        );
58    }
59
60    pub fn draw_text(&mut self, string: &str, x: i32, y: i32, size: f32, color: Rgb<u8>) {
61        let font = self.font.clone();
62
63        imageproc::drawing::draw_text_mut(
64            self.get_image_mut(),
65            color,
66            x,
67            y,
68            Scale::uniform(size),
69            &font,
70            string,
71        );
72    }
73
74    pub fn dimensions(&self) -> (u32, u32) {
75        self.get_image().dimensions()
76    }
77
78    pub fn width(&self) -> u32 {
79        self.get_image().width()
80    }
81
82    pub fn height(&self) -> u32 {
83        self.get_image().height()
84    }
85
86    pub fn clear(&mut self) {
87        self.get_image_mut().fill(255)
88    }
89
90    pub fn get_image(&self) -> &RgbImage {
91        self.handler.get_image()
92    }
93
94    pub fn get_image_mut(&mut self) -> &mut RgbImage {
95        self.handler.get_image_mut()
96    }
97
98    pub fn update(&mut self) {
99        self.handler.update()
100    }
101}