Add ability to construct Sprites from byte slices
This commit is contained in:
parent
3b007f4a4c
commit
aae911f81b
22
src/lib.rs
22
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<B: AsRef<[u8]>>(bytes: B, x: i32, y: i32) -> Result<Self> {
|
||||
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
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue