Skip to content

Instantly share code, notes, and snippets.

View Aely0's full-sized avatar

Aely Aely0

View GitHub Profile
@juancampa
juancampa / egui_centerer.rs
Created March 16, 2023 13:50
Centering arbitrary UIs in egui
// Helper function to center arbitrary widgets. It works by measuring the width of the widgets after rendering, and
// then using that offset on the next frame.
fn centerer(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui)) {
ui.horizontal(|ui| {
let id = ui.id().with("_centerer");
let last_width: Option<f32> = ui.memory_mut(|mem| mem.data.get_temp(id));
if let Some(last_width) = last_width {
ui.add_space((ui.available_width() - last_width) / 2.0);
}
let res = ui