Crate egui[−][src]
Expand description
egui
: an easy-to-use GUI in pure Rust!
Try the live web demo: https://emilk.github.io/egui/index.html. Read more about egui at https://github.com/emilk/egui.
egui
is in heavy development, with each new version having breaking changes.
You need to have rust 1.51.0 or later to use egui
.
To quickly get started with egui, you can take a look at egui_template
which uses eframe
.
To create a GUI using egui you first need a CtxRef
(by convention referred to by ctx
).
Then you add a Window
or a SidePanel
to get a Ui
, which is what you’ll be using to add all the buttons and labels that you need.
Using egui
To see what is possible to build with egui you can check out the online demo at https://emilk.github.io/egui/#demo.
If you like the “learning by doing” approach, clone https://github.com/emilk/egui_template and get started using egui right away.
A simple example
Here is a simple counter that can be incremented and decremented using two buttons:
fn ui_counter(ui: &mut egui::Ui, counter: &mut i32) {
// Put the buttons and label on the same row:
ui.horizontal(|ui| {
if ui.button("-").clicked() {
*counter -= 1;
}
ui.label(counter.to_string());
if ui.button("+").clicked() {
*counter += 1;
}
});
}
In some GUI frameworks this would require defining multiple types and functions with callbacks or message handlers,
but thanks to egui
being immediate mode everything is one self-contained function!
Getting a Ui
Use one of SidePanel
, TopBottomPanel
, CentralPanel
, Window
or Area
to
get access to an Ui
where you can put widgets. For example:
egui::CentralPanel::default().show(&ctx, |ui| {
ui.add(egui::Label::new("Hello World!"));
ui.label("A shorter and more convenient way to add a label.");
if ui.button("Click me").clicked() {
/* take some action here */
}
});
Quick start
ui.label("This is a label");
ui.hyperlink("https://github.com/emilk/egui");
ui.text_edit_singleline(&mut my_string);
if ui.button("Click me").clicked() { }
ui.add(egui::Slider::new(&mut my_f32, 0.0..=100.0));
ui.add(egui::DragValue::new(&mut my_f32));
ui.checkbox(&mut my_boolean, "Checkbox");
#[derive(PartialEq)]
enum Enum { First, Second, Third }
let mut my_enum = Enum::First;
ui.horizontal(|ui| {
ui.radio_value(&mut my_enum, Enum::First, "First");
ui.radio_value(&mut my_enum, Enum::Second, "Second");
ui.radio_value(&mut my_enum, Enum::Third, "Third");
});
ui.separator();
ui.image(my_image, [640.0, 480.0]);
ui.collapsing("Click to see what is hidden!", |ui| {
ui.label("Not much, as it turns out");
});
Conventions
Conventions unless otherwise specified:
- angles are in radians
Vec2::X
is right andVec2::Y
is down.Pos2::ZERO
is left top.- Positions and sizes are measured in points. Each point may consist of many physical pixels.
Integrating with egui
Most likely you are using an existing egui
backend/integration such as eframe
, bevy_egui
,
or egui-miniquad
,
but if you want to integrate egui
into a new game engine, this is the section for you.
To write your own integration for egui you need to do this:
let mut ctx = egui::CtxRef::default();
// Game loop:
loop {
let raw_input: egui::RawInput = gather_input();
ctx.begin_frame(raw_input);
egui::CentralPanel::default().show(&ctx, |ui| {
ui.label("Hello world!");
if ui.button("Click me").clicked() {
/* take some action here */
}
});
let (output, shapes) = ctx.end_frame();
let clipped_meshes = ctx.tessellate(shapes); // create triangles to paint
handle_output(output);
paint(clipped_meshes);
}
Understanding immediate mode
egui
is an immediate mode GUI library. It is useful to fully grok what “immediate mode” implies.
Here is an example to illustrate it:
if ui.button("click me").clicked() {
take_action()
}
This code is being executed each frame at maybe 60 frames per second. Each frame egui does these things:
- lays out the letters
click me
in order to figure out the size of the button - decides where on screen to place the button
- check if the mouse is hovering or clicking that location
- chose button colors based on if it is being hovered or clicked
- add a
Shape::Rect
andShape::Text
to the list of shapes to be painted later this frame - return a
Response
with theclicked
member so the user can check for interactions
There is no button being created and stored somewhere.
The only output of this call is some colored shapes, and a Response
.
Read more about the pros and cons of immediate mode at https://github.com/emilk/egui#why-immediate-mode.
How widgets works
if ui.button("click me").clicked() { take_action() }
is short for
let button = egui::Button::new("click me");
if ui.add(button).clicked() { take_action() }
which is short for
let button = egui::Button::new("click me");
let response = button.ui(ui);
if response.clicked() { take_action() }
Button
uses the builder pattern to create the data required to show it. The Button
is then discarded.
Button
implements trait
Widget
, which looks like this:
pub trait Widget {
/// Allocate space, interact, paint, and return a [`Response`].
fn ui(self, ui: &mut Ui) -> Response;
}
Sizes
You can control the size of widgets using Ui::add_sized
.
ui.add_sized([40.0, 20.0], egui::DragValue::new(&mut my_value));
Code snippets
// Miscellaneous tips and tricks
ui.horizontal_wrapped(|ui|{
ui.spacing_mut().item_spacing.x = 0.0; // remove spacing between widgets
// `radio_value` also works for enums, integers, and more.
ui.radio_value(&mut some_bool, false, "Off");
ui.radio_value(&mut some_bool, true, "On");
});
ui.group(|ui|{
ui.label("Within a frame");
ui.set_min_height(200.0);
});
// A `scope` creates a temporary [`Ui`] in which you can change settings:
ui.scope(|ui|{
ui.visuals_mut().override_text_color = Some(egui::Color32::RED);
ui.style_mut().override_text_style = Some(egui::TextStyle::Monospace);
ui.style_mut().wrap = Some(false);
ui.label("This text will be red, monospace, and won't wrap to a new line");
}); // the temporary settings are reverted here
Re-exports
pub use epaint;
pub use epaint::emath;
pub use epaint as paint;
pub use emath as math;
pub use containers::*;
pub use layers::LayerId;
pub use layers::Order;
pub use style::Style;
pub use style::Visuals;
pub use widgets::*;
Modules
Color conversions and types.
Containers are pieces of the UI which wraps other pieces of UI. Examples: Window
, ScrollArea
, Resize
, etc.
Handles paint layers, i.e. how things are sometimes painted behind or in front of other things.
Menu bar functionality (very basic so far).
Helper module that wraps some Mutex types with different implementations.
All the data egui returns to the backend at the end of each frame.
egui supports around 1216 emojis in total. Here are some of the most useful: ∞⊗⎗⎘⎙⏏⏴⏵⏶⏷ ⏩⏪⏭⏮⏸⏹⏺■▶📾🔀🔁🔃 ☀☁★☆☐☑☜☝☞☟⛃⛶✔ ↺↻⟲⟳⬅➡⬆⬇⬈⬉⬊⬋⬌⬍⮨⮩⮪⮫ ♡ 📅📆 📈📉📊 📋📌📎📤📥🔆 🔈🔉🔊🔍🔎🔗🔘 🕓🖧🖩🖮🖱🖴🖵🖼🗀🗁🗋🗐🗑🗙🚫❓
egui theme (spacing, colors, etc).
Miscellaneous tools used by the rest of egui.
Macros
An assert that is only active when egui
is compiled with the egui_assert
feature
or with the debug_egui_assert
feature in debug builds.
Show debug info on hover when Context::set_debug_on_hover
has been turned on.
Structs
Two-dimension alignment, e.g. Align2::LEFT_TOP
.
A Mesh
within a clip rectangle.
This format is used for space-efficient color representation (32 bits).
Describes the font data and the sizes to use.
A simple grid layout.
egui tracks widgets frame-to-frame using Id
s.
Returned when we wrap some ui-code and want to return both the results of the inner function and the ui as a whole, e.g.:
Input state that egui updates each frame.
The data that egui persists between frames.
State of the modifier keys. These must be fed to egui.
All you probably need to know about a multi-touch gesture.
What egui emits each frame. The backend should use this.
Helper to paint shapes and text to a specific region on a specific layer.
Mouse or touch state.
A position on screen.
What the integrations provides to egui at the start of each frame.
A rectangular region of space.
0-1 linear space RGBA
color with premultiplied alpha.
What sort of interaction is a widget sensitive to?
Describes the width and color of a line.
An 8-bit texture containing font data.
this is a u64
as values of this kind can always be obtained by hashing
Unique identification of a touch occurrence (finger or pen or …). A Touch ID is valid until the finger is lifted. A new ID is used for the next touch.
This is what you use to place widgets.
Describes a widget such as a crate::Button
or a crate::TextEdit
.
Enums
left/center/right or top/center/bottom alignment for e.g. anchors and layouts.
A mouse cursor icon.
Layout direction, one of LeftToRight
, RightToLeft
, TopDown
, BottomUp
.
An input event generated by the integration.
Which style of font: Monospace
or Proportional
.
Keyboard keys.
Mouse button (or similar for touch input)
A paint primitive such as a circle or a piece of text. Coordinates are all screen space points (not physical pixels).
One of a few categories of styles of text, e.g. body, button or heading.
In what phase a touch event is in.
The different types of built-in widgets in egui
Constants
Number of pointer buttons supported by egui, i.e. the number of possible states of PointerButton
.
Traits
Extends f32
, Vec2
etc with at_least
and at_most
as aliases for max
and min
.
Functions
Linear interpolation.
pos2(x,y) == Pos2::new(x, y)
Linearly remap a value from one range to another,
so that when x == from.start()
returns to.start()
and when x == from.end()
returns to.end()
.
Like remap
, but also clamps the value so that the returned value is always in the to
range.
vec2(x,y) == Vec2::new(x, y)
Helper function that adds a label when compiling with debug assertions enabled.