I'm making a simple checkers like game in druid. At this point I want to replace rectangles I used for prototyping with some pixel sprites. My initial plan was to try and load them in the root function I pass to
WindowDesc::new(root)
using
include_bytes!
, and the below function:
fn split(rows: usize, columns: usize, data: &[u8]) -> Vec<ImageBuf> {
let image: ImageBuf = ImageBuf::from_data(data).unwrap();
let mut ret: Vec<ImageBuf> = Vec::new();
let Size {width, height} = image.size();
let (row_h, column_w) = (height as usize / rows, width as usize / columns);
for idx in 0..(columns * rows) {
let x = (idx % columns) as u32;
let y = (idx / columns) as u32;
let mut frag = SubImage::new(&image,
x * column_w as u32,
y * row_h as u32,
(x+1) * column_w as u32,
(y+1) * row_h as u32);
// I'm not sure how to convert SubImage into ImageBuf here...
}
ret
}
However I've encountered few problems. First being that I didn't find any way to get ImageBuf from SubImage. Second being that PaintCtx::draw_image() takes in a reference to Bitmap struct which seems to be a part of d2d sub-crate within piet - and I assume is used by the graphical backend and is not intended to be used by the user.
What is an idiomatic and conventional way to load and display image in druid at some x and y in widget canvas (without requirement to keep it in filesystem as dependency)?
I would advise you to use the
imagecrate, to load the image (you did not specify the format, so I used a RGBA png with 4 bytes per pixel in my example).Vec<u8>ctx.make_imageandctx.draw_imageHere is a full example based on the
custom_widgetexample:You will need these dependencies:
and a PNG picture using RGBA8 format named
my_image.pngin the same directory as yourmain.rs.