added underdeveloped but working image support (no freeing or samplers)
This commit is contained in:
63
src/core/image.rs
Normal file
63
src/core/image.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use image::DynamicImage;
|
||||
|
||||
use crate::{Color, TextureHandle, Widget, WidgetFnRet, render::RectPrimitive};
|
||||
|
||||
pub struct Image {
|
||||
handle: Option<TextureHandle>,
|
||||
}
|
||||
|
||||
impl<Ctx> Widget<Ctx> for Image {
|
||||
fn draw(&self, painter: &mut crate::Painter<Ctx>) {
|
||||
if let Some(handle) = &self.handle {
|
||||
painter.draw_texture(handle);
|
||||
} else {
|
||||
painter.write(RectPrimitive {
|
||||
color: Color::MAGENTA,
|
||||
inner_radius: 0.0,
|
||||
radius: 0.0,
|
||||
thickness: 0.0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn image<Ctx>(image: impl LoadableImage) -> WidgetFnRet!(Image, Ctx) {
|
||||
let image = match image.get_image() {
|
||||
Ok(image) => Some(image),
|
||||
Err(e) => {
|
||||
println!("Failed to load image: {e}");
|
||||
None
|
||||
}
|
||||
};
|
||||
move |ui| Image {
|
||||
handle: image.map(|image| ui.add_texture(image)),
|
||||
}
|
||||
}
|
||||
|
||||
pub trait LoadableImage {
|
||||
fn get_image(self) -> Result<DynamicImage, String>;
|
||||
}
|
||||
|
||||
impl LoadableImage for &str {
|
||||
fn get_image(self) -> Result<DynamicImage, String> {
|
||||
image::open(self).map_err(|e| format!("{e:?}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl LoadableImage for String {
|
||||
fn get_image(self) -> Result<DynamicImage, String> {
|
||||
image::open(self).map_err(|e| format!("{e:?}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl<const LEN: usize> LoadableImage for &[u8; LEN] {
|
||||
fn get_image(self) -> Result<DynamicImage, String> {
|
||||
image::load_from_memory(self).map_err(|e| format!("{e:?}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl LoadableImage for DynamicImage {
|
||||
fn get_image(self) -> Result<DynamicImage, String> {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user