Display & Scale Images in egui — Rust GUI #17
Video: Display & Scale Images in egui — Rust GUI #17 by Taught by Celeste AI - AI Coding Coach
Watch full page →Display & Scale Images in egui — Rust GUI #17
In this tutorial, you'll learn how to build an image gallery app in Rust using egui, featuring thumbnails and zoom functionality. We'll cover embedding images at compile time, displaying clickable images, and controlling image scaling with egui's utilities.
Code
use egui::{Image, Sense, Vec2};
use egui_extras::image::{load_image_bytes, RetainedImage};
// Embed an image at compile time using include_image!
let my_image = egui::include_image!("my_photo.png");
// Load a PNG image at runtime (requires egui_extras::install_image_loaders)
let image_bytes = include_bytes!("my_photo.png");
let retained_image = RetainedImage::from_image_bytes("my_photo.png", image_bytes).unwrap();
fn ui_example(ui: &mut egui::Ui) {
// Display a thumbnail with max width and rounded corners
ui.add(
Image::new(my_image.texture_id(ui.ctx()), my_image.size_vec2())
.max_width(100.0) // limit width to 100 pixels
.rounding(4.0) // corner radius for rounded corners
.sense(Sense::click()) // make image clickable
);
// Zoomed image scaled to exact size
let zoom_factor = 2.0;
let zoomed_size = my_image.size_vec2() * zoom_factor;
ui.add(
Image::new(my_image.texture_id(ui.ctx()), zoomed_size)
.fit_to_exact_size() // scale image exactly to zoomed_size
);
}
Key Points
- Use
egui::include_image!to embed images at compile time for easy bundling. - Load PNG images at runtime with
egui_extras::install_image_loadersandRetainedImage. Image::new()supports chaining methods likemax_width,rounding, andsense(click)to customize appearance and interactivity.fit_to_exact_size()enables precise control over image scaling, useful for zoom effects.- Organize your app with multiple modules and use
pub(crate)to share fields internally across them.