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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use crate::drawing::Renderable;
use crate::image::Image;
use crate::Graphics;
use graphics_shapes::coord::Coord;
use std::ops::Neg;

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum DrawOffset {
    TopLeft,
    Center,
    Custom(Coord),
}

#[derive(Debug, Clone)]
pub struct RenderableImage {
    image: Image,
    xy: Coord,
    offset: DrawOffset,
}

impl RenderableImage {
    pub fn new(image: Image, xy: Coord, offset: DrawOffset) -> Self {
        Self { image, xy, offset }
    }
}

impl RenderableImage {
    pub fn set_position<P: Into<Coord>>(&mut self, new_position: P) {
        self.xy = new_position.into();
    }

    pub fn update_position<P: Into<Coord>>(&mut self, delta: P) {
        self.xy = self.xy + delta.into();
    }

    pub fn set_offset(&mut self, offset: DrawOffset) {
        self.offset = offset;
    }
}

impl Renderable<Image> for RenderableImage {
    fn render(&self, graphics: &mut Graphics) {
        let offset = match self.offset {
            DrawOffset::TopLeft => (0, 0).into(),
            DrawOffset::Center => (
                ((self.image.width() / 2) as isize).neg(),
                ((self.image.height() / 2) as isize).neg(),
            )
                .into(),
            DrawOffset::Custom(coord) => coord,
        };

        graphics.draw_image(self.xy + offset, &self.image);
    }
}