diff --git a/src/lib.rs b/src/lib.rs index 1fd3e29..9ecd00c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -216,6 +216,28 @@ impl Sprite { }) } + /// Create a new sprite using a slice of bytes, like what is returned from `include_bytes!` + /// + /// Don't forget to call [`draw()`](Self::draw()) after this. + /// ``` + /// # use cat_box::*; + /// let bytes = include_bytes!("../duck.png"); + /// let s = Sprite::from_bytes(bytes, 500, 400).unwrap(); + /// ``` + pub fn from_bytes>(bytes: B, x: i32, y: i32) -> Result { + let ops = RWops::from_bytes(bytes.as_ref())?; + let surf = ops.load()?; + + let srect = surf.rect(); + let dest_rect: Rect = Rect::from_center((x, y), srect.width(), srect.height()); + + Ok(Self { + rect: dest_rect, + surf, + angle: 0.0, + }) + } + /// Draws the sprite to the window. This should only be called inside your main event loop. /// /// ```no_run diff --git a/src/main.rs b/src/main.rs index dbc0ca2..1fb2940 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,10 +8,12 @@ fn main() { let mut s = Sprite::new("duck.png", 500, 400).unwrap(); let mut s2 = Sprite::new("duck.png", 400, 500).unwrap(); + let bytes = include_bytes!("../duck.png"); + let mut coll = SpriteCollection::new(); for n in 0..10 { for o in 0..8 { - let x = Sprite::new("duck.png", n * 100, o * 100).unwrap(); + let x = Sprite::from_bytes(bytes, n * 100, o * 100).unwrap(); coll.push(x); } }