Created
March 16, 2023 13:50
-
-
Save juancampa/faf3525beefa477babdad237f5e81ffe to your computer and use it in GitHub Desktop.
Centering arbitrary UIs in egui
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
.scope(|ui| { | |
add_contents(ui); | |
}) | |
.response; | |
let width = res.rect.width(); | |
ui.memory_mut(|mem| mem.data.insert_temp(id, width)); | |
// Repaint if width changed | |
match last_width { | |
None => ui.ctx().request_repaint(), | |
Some(last_width) if last_width != width => ui.ctx().request_repaint(), | |
Some(_) => {} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment