Browse Source

Add example of loading and showing an image with eframe/egui

Closes https://github.com/emilk/egui/pull/700
pull/702/head
Emil Ernerfeldt 3 years ago
parent
commit
6902151a96
  1. 1
      Cargo.lock
  2. 3
      eframe/Cargo.toml
  3. 47
      eframe/examples/image.rs
  4. BIN
      eframe/examples/rust-logo-512x512.png
  5. 1
      eframe/examples/rust-logo-license.txt

1
Cargo.lock

@ -784,6 +784,7 @@ dependencies = [
"egui_glium",
"egui_web",
"epi",
"image",
]
[[package]]

3
eframe/Cargo.toml

@ -34,6 +34,9 @@ egui_glium = { version = "0.14.0", path = "../egui_glium", default-features = fa
[target.'cfg(target_arch = "wasm32")'.dependencies]
egui_web = { version = "0.14.0", path = "../egui_web", default-features = false }
[dev-dependencies]
image = { version = "0.23", default-features = false, features = ["png"] }
[features]
default = ["default_fonts"]

47
eframe/examples/image.rs

@ -0,0 +1,47 @@
use eframe::{egui, epi};
#[derive(Default)]
struct MyApp {
texture: Option<egui::TextureId>,
}
impl epi::App for MyApp {
fn name(&self) -> &str {
"Show an image with eframe/egui"
}
fn update(&mut self, ctx: &egui::CtxRef, frame: &mut epi::Frame<'_>) {
if self.texture.is_none() {
// Load the image:
let image_data = include_bytes!("rust-logo-512x512.png");
use image::GenericImageView;
let image = image::load_from_memory(image_data).expect("Failed to load image");
let image_buffer = image.to_rgba8();
let size = (image.width() as usize, image.height() as usize);
let pixels = image_buffer.into_vec();
assert_eq!(size.0 * size.1 * 4, pixels.len());
let pixels: Vec<_> = pixels
.chunks_exact(4)
.map(|p| egui::Color32::from_rgba_unmultiplied(p[0], p[1], p[2], p[3]))
.collect();
// Allocate a texture:
let texture = frame
.tex_allocator()
.alloc_srgba_premultiplied(size, &pixels);
self.texture = Some(texture);
}
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("Here is an image for you:");
if let Some(texture) = self.texture {
ui.image(texture, egui::Vec2::splat(256.0));
}
});
}
}
fn main() {
let options = eframe::NativeOptions::default();
eframe::run_native(Box::new(MyApp::default()), options);
}

BIN
eframe/examples/rust-logo-512x512.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

1
eframe/examples/rust-logo-license.txt

@ -0,0 +1 @@
Rust logo by Mozilla, from https://github.com/rust-lang/rust-artwork
Loading…
Cancel
Save