Replies: 1 comment
-
Hi! use eframe::egui::*;
use eframe::*;
fn generate_random_image(width: usize, height: usize, offset: usize) -> Vec<u8> {
(0..(width * height)).map(|i| if (offset + i) % 17 == 0 { 0 } else { 0xff }).collect()
}
pub struct Application {
/// The texture we want to draw.
texture: TextureHandle,
/// Height of ui components.
ui_components_allocated_height: f32,
}
impl Application {
pub fn new(cc: &CreationContext<'_>) -> Self {
let raw = generate_random_image(128, 128, 0);
let img = ColorImage::from_gray([128, 128], &raw);
let texture = cc.egui_ctx.load_texture("noise", img, TextureOptions::NEAREST);
Self { texture, ui_components_allocated_height: 0. }
}
}
impl App for Application {
fn update(&mut self, ctx: &eframe::egui::Context, _frame: &mut eframe::Frame) {
CentralPanel::default().show(ctx, |ui| {
ui.vertical(|ui| {
// Heading
ui.heading("Textures");
// The image/texture
ui.add(Image::new(egui::load::SizedTexture::new(
// The texture's id
self.texture.id(),
// Allocate the size for the texture, but subtract the amount of height the other ui components need to be drawn and not be "cropped"
vec2(ui.available_width(), ui.available_height() - self.ui_components_allocated_height),
)));
// Measure size before allocating the other ui components
let before_ui_components = ui.min_rect();
// The other ui elements
ui.label("A label at the bottom");
ui.label("A label at the bottom");
ui.label("A label at the bottom");
// Measure size after allocating the all of the other ui components
let after_ui_components = ui.min_rect();
// Calculate the height needed to draw the other ui elements
let height_taken_by_ui_components = after_ui_components.height() - before_ui_components.height();
// Store the value
self.ui_components_allocated_height = height_taken_by_ui_components;
});
});
}
} There may be other ways of overcoming the issue, but this is how I would do this if I really had to. This implementation also works horizontally if you change the code a little to work on the x axis instead. You could also use a ScrollArea, but that would involve having the user scroll down, which may not be what you want. I am happy to answer all of your questions if you have any! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm trying to figure out how to get egui to scale a texture to fill the available space in a window taking into account other items that are in the window.
Below, I generate a texture in code and sandwich it between a heading and a label. I'd like for the texture to scale to fill the available window if I resize the window, while keeping the label and heading visible. I know I can specify the exact width and height of the texture, so one way is to manually account for all widgets in the window and do the math. Is there a better way to do this?
Beta Was this translation helpful? Give feedback.
All reactions