logo
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
use std::rc::Rc;

use super::{Graphics, Sprite, Texture};

/// A fixed-size sprite that displays a single texture.
#[derive(Default, Clone, Debug)]
pub struct ImageSprite {
    pub inner: Sprite,
    /// The texture being displayed, or None if none.
    pub texture: Option<Rc<dyn Texture>>,
}

impl ImageSprite {
    pub fn new(texture: Option<Rc<dyn Texture>>) -> Self {
        Self {
            inner: Sprite::new(),
            texture,
        }
    }

    // override
    pub fn draw(&self, gfx: &Box<dyn Graphics>) {
        if let Some(ref texture) = self.texture {
            gfx.draw_texture(texture, 0.0, 0.0);
        }
    }

    // override
    pub fn natural_width(&self) -> f32 {
        if let Some(ref texture) = self.texture {
            texture.width() as f32
        } else {
            0.0
        }
    }

    // override
    pub fn natural_height(&self) -> f32 {
        if let Some(ref texture) = self.texture {
            texture.height() as f32
        } else {
            0.0
        }
    }
}

impl AsRef<Sprite> for ImageSprite {
    fn as_ref(&self) -> &Sprite {
        &self.inner
    }
}