Struct mooeye::ui::UiElementBuilder

source ·
pub struct UiElementBuilder<T: Copy + Eq + Hash> { /* private fields */ }
Expand description

A builder struct for UiElements. Allows changing of all relevant fields of the built element, and contains shorthand function for changing the components of the elements layout. Also contains shorthand functions for some very frequently used combination of layout settings.

Implementations§

source§

impl<T: Copy + Eq + Hash> UiElementBuilder<T>

source

pub fn new(id: u32, content: impl UiContent<T> + 'static) -> Self

Creates a new builder building an element containing the specified content with the specified id. If built directly, all fields except content will be set to their default values or the values set in the to_element function of the passed con.

source

pub fn with_child(self, element: UiElement<T>) -> Self

If the elements content is a container, the passed element is added to it. Otherwise, the passed element is discarded.

Examples found in repository?
examples/ui_examples/d_containers.rs (line 146)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Predefine some visuals so we don't have to do it for every element.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        // You can also create 'custom' visuals that allow you to set the thickness of each border & radius of each corner separately.

        let vis2 = ui::Visuals::new_custom(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            [4., 1., 4., 1.],
            [2., 2., 2., 2.],
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new_custom(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            [16., 8., 8., 8.],
            [12., 2., 2., 12.],
        );

        // Note that the constructor now returns a Result.
        // This is neccessary as the 'add' function used to add UI elements to grid containers can fail, thus failing the constructor.

        // The first container we use is a vertical box simply laying out elements from top to bottom.
        let mut ver_box = ui::containers::VerticalBox::new();
        // We can manually change the spacing between elements in the box
        ver_box.spacing = 10.;
        // first, we need to add all the children to this vertical box.
        // We'll just use TextElement for now, but these can also be images, sprites, placeholders or more containers.
        for i in 0..8 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis2)
                .build();
            // Add the element to the box. This cannot fail for non-grid containers, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox, it would simply consume the element and do nothing.
            ver_box.add(element);
        }
        // After adding all children, we can convert to a UiElement and style the box like we would style an other element. The usual pattern here is to shadow the variable to avoid use-after-move.
        let ver_box = ver_box
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            // Using larger padding to accomodate our thick borders.
            .with_padding((24., 16., 16., 16.))
            .build();

        // Another container we can use is GridBox. A GridBox needs to be initialized with a set height and width and cannot be extended.
        let mut grid = ui::containers::GridBox::new(4, 4);
        // The contents of a grid box are initialized as empty elements.  We'll add buttons to the diagonal of the grid.
        for i in 0..4 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis)
                // Elements can be given alignment and will align within their respecitive cell in the grid.
                .with_alignment(ui::Alignment::Max, None)
                .build();
            // Add the element to the box. This can fail, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox.
            grid.add(element, i, i)?;
        }

        // We'll also create our usual back button and put it into the top right of the grid.

        let back = graphics::Text::new("Back!")
            .set_font("Bahnschrift")
            .set_scale(28.)
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .with_hover_visuals(hover_vis)
            .build();

        // This time, we'll enhance our back button a bit by using an icon that is displayed over the top left corner.
        // To achieve this, we'll use a StackBox.
        let mut stack = ui::containers::StackBox::new();
        stack.add(back);
        // The add_top function adds something to the top of a stack box. Creating and adding an element can be done inline.
        stack.add_top(
            graphics::Image::from_path(ctx, "/moo.png")?
                .to_element_builder(0, ctx)
                // We'll align the icon to the top right
                .with_alignment(ui::Alignment::Min, ui::Alignment::Min)
                // and offset it slightly
                .with_offset(-10., -10.)
                .build(),
        )?;
        // to_element is a shorthand for to_element_builder().build() if we want to simply take the default builder and not change anything.
        let stack = stack.to_element(0, ctx);

        // Now, we add the stack to the grid.
        grid.add(stack, 3, 0)?;

        // And finally build the grid.
        let grid = grid
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            .with_padding((24., 16., 16., 16.))
            .build();

        // The horizontal box is exactly the same as the vertical box except for orientation.
        // We will use a horizontal box to contain the boxes created so far.
        // if you don't want to create multiple variables, adding of children can be done inline for non-grid
        // containers by using .with_child.
        Ok(Self {
            gui: ui::containers::HorizontalBox::new()
                .to_element_builder(0, ctx)
                .with_child(ver_box)
                .with_child(grid)
                .build(),
        })
    }
More examples
Hide additional examples
examples/ui_examples/e_messages.rs (line 143)
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    pub fn new(ctx: &Context) -> GameResult<Self> {


        // This title will change based on transitions whenever certain buttons are clicked.
        let title = Text::new("Move this element with the buttons.\nYou have not yet clicked a button.")
        // First, we style the title.
        .set_font("Bahnschrift")
        .set_scale(28.)
        .to_owned()
        .to_element_builder(0, ctx)
        // Then, we add a message handler to the element.
        .with_message_handler(

            // The message handle receives a set of messages and a mutable transition vector.
        |messages,_,transitions| {
            let ids = [11,12,13,21,22,23,];

            // We check if any of the buttons that interest us were clicked in the last frame.
            for id in ids{
                for message in messages{
                    if *message == ui::UiMessage::<()>::Clicked(id){

                        // If yes, we add a new transition to the vector.
                        transitions.push_back(
                            // Transitions are initalized with the duration they should take to complete and augmented via the builder pattern.
                            ui::Transition::new(Duration::ZERO)
                            // Here, we add a new content that will replace the old text once the transition completes.
                            .with_new_content(Text::new(format!(
                                "Move this element with the buttons.\nYou clicked a button with id {}.",
                                id
                            ))
                            .set_font("Bahnschrift")
                            .set_scale(24.)
                            .to_owned())
                        )
                        
                    }
                }
            }
        })
        .build();

        // Define a general visual style to use for all buttons.
        let vis = ui::Visuals::new(
            Color::from_rgb(77, 109, 191),
            Color::from_rgb(55, 67, 87),
            2.,
            4.,
        );

        // Create a grid box to hold all buttons.
        let mut grid_box = ui::containers::GridBox::new(2, 3);

        // Now, we create 6 buttons to move the element to all possible vertical and horizontal alignments and add them to the grid.
        let vert_up = Text::new(" ^ ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(11, ctx)
            .with_visuals(vis) 
            // We can also set a sound to be played on click/key press
            .with_trigger_sound(ggez::audio::Source::new(ctx, "/blipSelect.wav").ok())
            .build();
        grid_box
            .add(vert_up, 0, 0)?;

        let vert_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(12, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_ce, 0, 1)?;

        let vert_do = Text::new(" v ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(13, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_do, 0, 2)?;

        let hor_up = Text::new(" < ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(21, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_up, 1, 0)?;

        let hor_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(22, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_ce, 1, 1)?;

        let hor_do = Text::new(" > ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(23, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_do, 1, 2)?;

        // The well-known back button will take us back to scene select.
        let back = Text::new("Back")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .as_fill()
            .build();

        
        // We create a general VBox to contain our UI
        // We can create Vertical and Horizontal Boxes with the 'spaced' constructor to set its spacing value.
        let gui_box = ui::containers::VerticalBox::new_spaced(6.)
        .to_element_builder(0, ctx)
        // We put the title, grid and back button together in a box.
        .with_child(title)
        .with_child(grid_box.to_element(30, ctx))
        .with_child(back)
        .with_size(ui::Size::Shrink(128., f32::INFINITY), ui::Size::Shrink(0., f32::INFINITY))
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(120, 170, 200),
            Color::from_rgb(55, 67, 87),
            2.,
            0.,
        ))
        // Another message handler. Along with the messages and transition vector as discussed above, we also receive a layout struct
        // that represents the layout struct of the element in the moment the transition was initialized. This allows us to only change
        // the relevant parts of the layout without having to recreate it from scratch.
        .with_message_handler(|messages, layout, transitions| {
            // This guards prevent spam clicking a button from locking up the element with 1.5-second transitions.
            if !transitions.is_empty() {
                return;
            }
            let vert_map = HashMap::from([
                (11, ui::Alignment::Min),
                (12, ui::Alignment::Center),
                (13, ui::Alignment::Max),
            ]);
            let hor_map = HashMap::from([
                (21, ui::Alignment::Min),
                (22, ui::Alignment::Center),
                (23, ui::Alignment::Max),
            ]);
            // Check if any vertical buttons were clicked.
            for (key, val) in vert_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        // If yes, add a transition.
                        ui::Transition::new(Duration::from_secs_f32(1.5))
                        // This time, we don't change the content, but the layout.
                        // Layout, visuals and hover_visuals are not  changed on completion like content, but instead applied gradually.
                        .with_new_layout(ui::Layout{
                            y_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
            // Repeat for horizontal keys.
            for (key, val) in hor_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        ui::Transition::new(Duration::from_secs_f32(1.5)).with_new_layout(ui::Layout{
                            x_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
        })
        .build();

        // Finally, we wrap our gui_box into a space-filling stack pane so we have a place to later add further elements

        Ok(Self {
            gui: ui::containers::StackBox::new()
            .to_element_builder(100, ctx)
            .as_fill()
            .with_child(gui_box)
            .build()
        })
    }
source

pub fn with_conditional_child( self, condition: bool, element: UiElement<T> ) -> Self

If the elements content is a container and the passed conditional evaluates to true, the passed element is added to it. Otherwise, the passed element is discarded.

source

pub fn with_visuals(self, visuals: Visuals) -> Self

Sets the elements visuals.

Examples found in repository?
examples/ui_examples/c_uielement.rs (lines 37-41)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    pub fn new(ctx: &Context) -> Self{
        // The scene constructor is usually the place where we create the state of our UI.
        // In this case, we will only create a single element.

        let text_element = 
        // First, we create anything implementing UiContent. ggez Image and Text do that, so we'll use a Text.
        // You can format that text as you can in ggez, so let's use our custom font and set a larger size.
        graphics::Text::new("Take me back!") 
        .set_font("Bahnschrift")
        .set_scale(32.)
        // Then we'll convert that content to an UiElementBuilder. We have to give it an ID.
        // ID 0 is reserved for elements not sending messages, but since we want to use the Text as a button, we'll use 1.
        .to_owned()
        .to_element_builder(1, ctx) 
        // We can now use the functions of UiElementBuilder to style and position our element.
        // First, we'll set the visuals using a Visuals struct.
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(49, 53, 69),
            Color::from_rgb(250, 246, 230),
            4.,8. 
        ))
        // Additionally, you can add keycodes that make your element respond to key presses as it would respond to clicks
        .with_trigger_key(winit::event::VirtualKeyCode::A)
        // We can also set the alignment within the window...
        .with_alignment(ui::Alignment::Min, ui::Alignment::Center)
        // ... offset the element (note that we can pass None into most of these functions to leave the presets for one dimension untouched) ...
        .with_offset(25., None)
        // ... or set its padding ...
        .with_padding((5., 10., 5., 10.))
        // ... and size. Here, we use a special method 'shrink' that sets the size of both dimension to shrink without changing their boundaries.
        // Using the function .with_size would require us to also pass in boundaries.
        .as_shrink()
        // Finally, we build the element.
        .build();

        Self{gui: text_element}
    }
More examples
Hide additional examples
examples/ui_examples/g_selector_scene.rs (line 46)
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Defining visuals

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        // Creating main grid

        let mut grid = ui::containers::GridBox::new(3, 2);

        let contents = ["Scene", "UiElement", "Container", "Messages", "Sprites"];

        for (i, &cont) in contents.iter().enumerate() {
            grid.add(
                graphics::Text::new(cont)
                    .set_scale(32.)
                    .to_owned()
                    .to_element_builder(i as u32 + 1, ctx)
                    .with_visuals(vis)
                    .with_hover_visuals(hover_vis)
                    .with_tooltip(
                        graphics::Text::new(format!(
                            "Click to look at the Scene created in the file {}.",
                            contents[i].to_lowercase()
                        ))
                        .set_scale(24.)
                        .set_wrap(true)
                        .set_bounds(glam::Vec2::new(240., 500.))
                        .to_owned()
                        .to_element_builder(0, ctx)
                        .with_visuals(hover_vis)
                        .build(),
                    )
                    .build(),
                i % 3,
                i / 3,
            )?;
        }

        // Add quit button

        grid.add(
            graphics::Text::new("Quit")
                .set_scale(32.)
                .to_owned()
                .to_element_builder(6, ctx)
                .with_visuals(vis)
                .with_hover_visuals(hover_vis)
                .build(),
            2,
            1,
        )?;

        Ok(Self {
            gui: grid.to_element_builder(0, ctx).build(),
        })
    }
examples/ui_examples/f_sprites.rs (line 70)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Reusing the visuals from E.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            1.,
            0.,
        );

        // A sprite can be loaded by specifying a path, just like an Image.
        // Additionaly, you need to inform the sprite of the grid size of its sheet and the duration each frame is displayed.
        let ui_sprite = sprite::Sprite::from_path(
            "/moo-sheet_16_16.png",
            ctx,
            16,
            24,
            Duration::from_secs_f32(0.25),
        )?
        // Just like any UI element, a sprite can have visuals, tooltip, ect.
        .to_element_builder(1, ctx)
        .scaled(5., 5.)
        .with_visuals(vis)
        .with_hover_visuals(hover_vis)
        .with_tooltip(
            graphics::Text::new("This is a sprite! Click it to end the scene.")
                .set_scale(28.)
                .set_font("Bahnschrift")
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(cont_vis)
                .build(),
        )
        .as_shrink()
        .build();

        // Sprites can also be initiated from a sprite pool, to make repeated file system access unneccessary
        // and streamline loading of multiple sprites. This requires sprites in the folder to be formatted appropriately.

        let sprite_pool = sprite::SpritePool::new()
            // with_folder loads all .png/.bmp/.jpg/.jpeg files from the passed folder and optionally its subfolders
            .with_folder(ctx, "/", true);

        // We can now init a sprite from the pool. Sprites are saved in the pool with a key corresponding to their relative path
        // (from the resource folder) with the format information and file ending removed.
        let non_ui_sprite = sprite_pool.init_sprite("/mage-sheet", Duration::from_secs_f32(0.2))?;

        // you can also initialize a sprite pool without any folder at all
        let mut sprite_pool2 = sprite::SpritePool::new();

        // in this case, you can use lazy initialisation of sprites to fill the sprite pool only with those sprites currently needed.
        // Lazy initilisation draws from the pool if possible, from the file system if needed (and loads into the pool in this case) and panics if it can't find anything in the fs.
        // Requires a mutable sprite pool!
        // For testing purposes, we are loading a sprite we have already loaded - this should be drawn from the pool.
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/mage-sheet", Duration::from_secs_f32(0.5))?;
        // now load the correct sprite
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/moo-sheet", lazy_sprite.get_frame_time())?;

        Ok(Self {
            gui: ui_sprite,
            sprite: non_ui_sprite,
            sprite2: lazy_sprite,
            pos: Vec2::new(50., 200.),
            v: Vec2::new(4., 4.),
        })
    }
examples/ui_examples/d_containers.rs (line 68)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Predefine some visuals so we don't have to do it for every element.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        // You can also create 'custom' visuals that allow you to set the thickness of each border & radius of each corner separately.

        let vis2 = ui::Visuals::new_custom(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            [4., 1., 4., 1.],
            [2., 2., 2., 2.],
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new_custom(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            [16., 8., 8., 8.],
            [12., 2., 2., 12.],
        );

        // Note that the constructor now returns a Result.
        // This is neccessary as the 'add' function used to add UI elements to grid containers can fail, thus failing the constructor.

        // The first container we use is a vertical box simply laying out elements from top to bottom.
        let mut ver_box = ui::containers::VerticalBox::new();
        // We can manually change the spacing between elements in the box
        ver_box.spacing = 10.;
        // first, we need to add all the children to this vertical box.
        // We'll just use TextElement for now, but these can also be images, sprites, placeholders or more containers.
        for i in 0..8 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis2)
                .build();
            // Add the element to the box. This cannot fail for non-grid containers, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox, it would simply consume the element and do nothing.
            ver_box.add(element);
        }
        // After adding all children, we can convert to a UiElement and style the box like we would style an other element. The usual pattern here is to shadow the variable to avoid use-after-move.
        let ver_box = ver_box
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            // Using larger padding to accomodate our thick borders.
            .with_padding((24., 16., 16., 16.))
            .build();

        // Another container we can use is GridBox. A GridBox needs to be initialized with a set height and width and cannot be extended.
        let mut grid = ui::containers::GridBox::new(4, 4);
        // The contents of a grid box are initialized as empty elements.  We'll add buttons to the diagonal of the grid.
        for i in 0..4 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis)
                // Elements can be given alignment and will align within their respecitive cell in the grid.
                .with_alignment(ui::Alignment::Max, None)
                .build();
            // Add the element to the box. This can fail, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox.
            grid.add(element, i, i)?;
        }

        // We'll also create our usual back button and put it into the top right of the grid.

        let back = graphics::Text::new("Back!")
            .set_font("Bahnschrift")
            .set_scale(28.)
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .with_hover_visuals(hover_vis)
            .build();

        // This time, we'll enhance our back button a bit by using an icon that is displayed over the top left corner.
        // To achieve this, we'll use a StackBox.
        let mut stack = ui::containers::StackBox::new();
        stack.add(back);
        // The add_top function adds something to the top of a stack box. Creating and adding an element can be done inline.
        stack.add_top(
            graphics::Image::from_path(ctx, "/moo.png")?
                .to_element_builder(0, ctx)
                // We'll align the icon to the top right
                .with_alignment(ui::Alignment::Min, ui::Alignment::Min)
                // and offset it slightly
                .with_offset(-10., -10.)
                .build(),
        )?;
        // to_element is a shorthand for to_element_builder().build() if we want to simply take the default builder and not change anything.
        let stack = stack.to_element(0, ctx);

        // Now, we add the stack to the grid.
        grid.add(stack, 3, 0)?;

        // And finally build the grid.
        let grid = grid
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            .with_padding((24., 16., 16., 16.))
            .build();

        // The horizontal box is exactly the same as the vertical box except for orientation.
        // We will use a horizontal box to contain the boxes created so far.
        // if you don't want to create multiple variables, adding of children can be done inline for non-grid
        // containers by using .with_child.
        Ok(Self {
            gui: ui::containers::HorizontalBox::new()
                .to_element_builder(0, ctx)
                .with_child(ver_box)
                .with_child(grid)
                .build(),
        })
    }
examples/ui_examples/e_messages.rs (line 80)
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
    pub fn new(ctx: &Context) -> GameResult<Self> {


        // This title will change based on transitions whenever certain buttons are clicked.
        let title = Text::new("Move this element with the buttons.\nYou have not yet clicked a button.")
        // First, we style the title.
        .set_font("Bahnschrift")
        .set_scale(28.)
        .to_owned()
        .to_element_builder(0, ctx)
        // Then, we add a message handler to the element.
        .with_message_handler(

            // The message handle receives a set of messages and a mutable transition vector.
        |messages,_,transitions| {
            let ids = [11,12,13,21,22,23,];

            // We check if any of the buttons that interest us were clicked in the last frame.
            for id in ids{
                for message in messages{
                    if *message == ui::UiMessage::<()>::Clicked(id){

                        // If yes, we add a new transition to the vector.
                        transitions.push_back(
                            // Transitions are initalized with the duration they should take to complete and augmented via the builder pattern.
                            ui::Transition::new(Duration::ZERO)
                            // Here, we add a new content that will replace the old text once the transition completes.
                            .with_new_content(Text::new(format!(
                                "Move this element with the buttons.\nYou clicked a button with id {}.",
                                id
                            ))
                            .set_font("Bahnschrift")
                            .set_scale(24.)
                            .to_owned())
                        )
                        
                    }
                }
            }
        })
        .build();

        // Define a general visual style to use for all buttons.
        let vis = ui::Visuals::new(
            Color::from_rgb(77, 109, 191),
            Color::from_rgb(55, 67, 87),
            2.,
            4.,
        );

        // Create a grid box to hold all buttons.
        let mut grid_box = ui::containers::GridBox::new(2, 3);

        // Now, we create 6 buttons to move the element to all possible vertical and horizontal alignments and add them to the grid.
        let vert_up = Text::new(" ^ ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(11, ctx)
            .with_visuals(vis) 
            // We can also set a sound to be played on click/key press
            .with_trigger_sound(ggez::audio::Source::new(ctx, "/blipSelect.wav").ok())
            .build();
        grid_box
            .add(vert_up, 0, 0)?;

        let vert_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(12, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_ce, 0, 1)?;

        let vert_do = Text::new(" v ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(13, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_do, 0, 2)?;

        let hor_up = Text::new(" < ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(21, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_up, 1, 0)?;

        let hor_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(22, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_ce, 1, 1)?;

        let hor_do = Text::new(" > ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(23, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_do, 1, 2)?;

        // The well-known back button will take us back to scene select.
        let back = Text::new("Back")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .as_fill()
            .build();

        
        // We create a general VBox to contain our UI
        // We can create Vertical and Horizontal Boxes with the 'spaced' constructor to set its spacing value.
        let gui_box = ui::containers::VerticalBox::new_spaced(6.)
        .to_element_builder(0, ctx)
        // We put the title, grid and back button together in a box.
        .with_child(title)
        .with_child(grid_box.to_element(30, ctx))
        .with_child(back)
        .with_size(ui::Size::Shrink(128., f32::INFINITY), ui::Size::Shrink(0., f32::INFINITY))
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(120, 170, 200),
            Color::from_rgb(55, 67, 87),
            2.,
            0.,
        ))
        // Another message handler. Along with the messages and transition vector as discussed above, we also receive a layout struct
        // that represents the layout struct of the element in the moment the transition was initialized. This allows us to only change
        // the relevant parts of the layout without having to recreate it from scratch.
        .with_message_handler(|messages, layout, transitions| {
            // This guards prevent spam clicking a button from locking up the element with 1.5-second transitions.
            if !transitions.is_empty() {
                return;
            }
            let vert_map = HashMap::from([
                (11, ui::Alignment::Min),
                (12, ui::Alignment::Center),
                (13, ui::Alignment::Max),
            ]);
            let hor_map = HashMap::from([
                (21, ui::Alignment::Min),
                (22, ui::Alignment::Center),
                (23, ui::Alignment::Max),
            ]);
            // Check if any vertical buttons were clicked.
            for (key, val) in vert_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        // If yes, add a transition.
                        ui::Transition::new(Duration::from_secs_f32(1.5))
                        // This time, we don't change the content, but the layout.
                        // Layout, visuals and hover_visuals are not  changed on completion like content, but instead applied gradually.
                        .with_new_layout(ui::Layout{
                            y_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
            // Repeat for horizontal keys.
            for (key, val) in hor_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        ui::Transition::new(Duration::from_secs_f32(1.5)).with_new_layout(ui::Layout{
                            x_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
        })
        .build();

        // Finally, we wrap our gui_box into a space-filling stack pane so we have a place to later add further elements

        Ok(Self {
            gui: ui::containers::StackBox::new()
            .to_element_builder(100, ctx)
            .as_fill()
            .with_child(gui_box)
            .build()
        })
    }
}


impl scene_manager::Scene for EScene {
    fn update(&mut self, ctx: &mut Context) -> Result<scene_manager::SceneSwitch, GameError> {
        // Nothing much to do here, except implement the back button functionality.

        let messages = self.gui.manage_messages(ctx, None);

        if messages.contains(&ui::UiMessage::Triggered(1)){
            // If it is, we end the current scene (and return to the previous one) by popping it off the stack.
            return Ok(scene_manager::SceneSwitch::pop(1));
        }

        if messages.contains(&ui::UiMessage::Triggered(13)){
            // If a certain button is pressed, add a small text element to the gui.
            self.gui.add_element(100,
                // using a duration box as a wrapper will remove the element after a set amount of time
                  ui::containers::DurationBox::new(
                    Duration::from_secs_f32(1.5),
                     graphics::Text::new("Just a small reminder that you pressed button 13.")
                     .set_font("Bahnschrift")
                     .set_wrap(true)
                     .set_bounds(glam::Vec2::new(200., 500.))
                     .set_scale(28.)
                     .to_owned()
                     .to_element_builder(0, ctx)
                     .with_visuals(ui::Visuals::new(
                        Color::from_rgb(77, 109, 191),
                        Color::from_rgb(55, 67, 87),
                        2.,
                        4.,
                    ))
                     .build()
                    ).to_element_builder(0, ctx)
                    .with_alignment(ui::Alignment::Center, ui::Alignment::Min)
                    .with_offset(0., 25.)
                    .build()
                    );
        }

        Ok(scene_manager::SceneSwitch::None)
    
    }
source

pub fn with_hover_visuals( self, hover_visuals: impl Into<Option<Visuals>> ) -> Self

Sets the elements hover_visuals. Pass in None to delete any existing hover_visuals.

Examples found in repository?
examples/ui_examples/g_selector_scene.rs (line 47)
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Defining visuals

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        // Creating main grid

        let mut grid = ui::containers::GridBox::new(3, 2);

        let contents = ["Scene", "UiElement", "Container", "Messages", "Sprites"];

        for (i, &cont) in contents.iter().enumerate() {
            grid.add(
                graphics::Text::new(cont)
                    .set_scale(32.)
                    .to_owned()
                    .to_element_builder(i as u32 + 1, ctx)
                    .with_visuals(vis)
                    .with_hover_visuals(hover_vis)
                    .with_tooltip(
                        graphics::Text::new(format!(
                            "Click to look at the Scene created in the file {}.",
                            contents[i].to_lowercase()
                        ))
                        .set_scale(24.)
                        .set_wrap(true)
                        .set_bounds(glam::Vec2::new(240., 500.))
                        .to_owned()
                        .to_element_builder(0, ctx)
                        .with_visuals(hover_vis)
                        .build(),
                    )
                    .build(),
                i % 3,
                i / 3,
            )?;
        }

        // Add quit button

        grid.add(
            graphics::Text::new("Quit")
                .set_scale(32.)
                .to_owned()
                .to_element_builder(6, ctx)
                .with_visuals(vis)
                .with_hover_visuals(hover_vis)
                .build(),
            2,
            1,
        )?;

        Ok(Self {
            gui: grid.to_element_builder(0, ctx).build(),
        })
    }
More examples
Hide additional examples
examples/ui_examples/f_sprites.rs (line 71)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Reusing the visuals from E.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            1.,
            0.,
        );

        // A sprite can be loaded by specifying a path, just like an Image.
        // Additionaly, you need to inform the sprite of the grid size of its sheet and the duration each frame is displayed.
        let ui_sprite = sprite::Sprite::from_path(
            "/moo-sheet_16_16.png",
            ctx,
            16,
            24,
            Duration::from_secs_f32(0.25),
        )?
        // Just like any UI element, a sprite can have visuals, tooltip, ect.
        .to_element_builder(1, ctx)
        .scaled(5., 5.)
        .with_visuals(vis)
        .with_hover_visuals(hover_vis)
        .with_tooltip(
            graphics::Text::new("This is a sprite! Click it to end the scene.")
                .set_scale(28.)
                .set_font("Bahnschrift")
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(cont_vis)
                .build(),
        )
        .as_shrink()
        .build();

        // Sprites can also be initiated from a sprite pool, to make repeated file system access unneccessary
        // and streamline loading of multiple sprites. This requires sprites in the folder to be formatted appropriately.

        let sprite_pool = sprite::SpritePool::new()
            // with_folder loads all .png/.bmp/.jpg/.jpeg files from the passed folder and optionally its subfolders
            .with_folder(ctx, "/", true);

        // We can now init a sprite from the pool. Sprites are saved in the pool with a key corresponding to their relative path
        // (from the resource folder) with the format information and file ending removed.
        let non_ui_sprite = sprite_pool.init_sprite("/mage-sheet", Duration::from_secs_f32(0.2))?;

        // you can also initialize a sprite pool without any folder at all
        let mut sprite_pool2 = sprite::SpritePool::new();

        // in this case, you can use lazy initialisation of sprites to fill the sprite pool only with those sprites currently needed.
        // Lazy initilisation draws from the pool if possible, from the file system if needed (and loads into the pool in this case) and panics if it can't find anything in the fs.
        // Requires a mutable sprite pool!
        // For testing purposes, we are loading a sprite we have already loaded - this should be drawn from the pool.
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/mage-sheet", Duration::from_secs_f32(0.5))?;
        // now load the correct sprite
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/moo-sheet", lazy_sprite.get_frame_time())?;

        Ok(Self {
            gui: ui_sprite,
            sprite: non_ui_sprite,
            sprite2: lazy_sprite,
            pos: Vec2::new(50., 200.),
            v: Vec2::new(4., 4.),
        })
    }
examples/ui_examples/d_containers.rs (line 109)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Predefine some visuals so we don't have to do it for every element.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        // You can also create 'custom' visuals that allow you to set the thickness of each border & radius of each corner separately.

        let vis2 = ui::Visuals::new_custom(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            [4., 1., 4., 1.],
            [2., 2., 2., 2.],
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new_custom(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            [16., 8., 8., 8.],
            [12., 2., 2., 12.],
        );

        // Note that the constructor now returns a Result.
        // This is neccessary as the 'add' function used to add UI elements to grid containers can fail, thus failing the constructor.

        // The first container we use is a vertical box simply laying out elements from top to bottom.
        let mut ver_box = ui::containers::VerticalBox::new();
        // We can manually change the spacing between elements in the box
        ver_box.spacing = 10.;
        // first, we need to add all the children to this vertical box.
        // We'll just use TextElement for now, but these can also be images, sprites, placeholders or more containers.
        for i in 0..8 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis2)
                .build();
            // Add the element to the box. This cannot fail for non-grid containers, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox, it would simply consume the element and do nothing.
            ver_box.add(element);
        }
        // After adding all children, we can convert to a UiElement and style the box like we would style an other element. The usual pattern here is to shadow the variable to avoid use-after-move.
        let ver_box = ver_box
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            // Using larger padding to accomodate our thick borders.
            .with_padding((24., 16., 16., 16.))
            .build();

        // Another container we can use is GridBox. A GridBox needs to be initialized with a set height and width and cannot be extended.
        let mut grid = ui::containers::GridBox::new(4, 4);
        // The contents of a grid box are initialized as empty elements.  We'll add buttons to the diagonal of the grid.
        for i in 0..4 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis)
                // Elements can be given alignment and will align within their respecitive cell in the grid.
                .with_alignment(ui::Alignment::Max, None)
                .build();
            // Add the element to the box. This can fail, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox.
            grid.add(element, i, i)?;
        }

        // We'll also create our usual back button and put it into the top right of the grid.

        let back = graphics::Text::new("Back!")
            .set_font("Bahnschrift")
            .set_scale(28.)
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .with_hover_visuals(hover_vis)
            .build();

        // This time, we'll enhance our back button a bit by using an icon that is displayed over the top left corner.
        // To achieve this, we'll use a StackBox.
        let mut stack = ui::containers::StackBox::new();
        stack.add(back);
        // The add_top function adds something to the top of a stack box. Creating and adding an element can be done inline.
        stack.add_top(
            graphics::Image::from_path(ctx, "/moo.png")?
                .to_element_builder(0, ctx)
                // We'll align the icon to the top right
                .with_alignment(ui::Alignment::Min, ui::Alignment::Min)
                // and offset it slightly
                .with_offset(-10., -10.)
                .build(),
        )?;
        // to_element is a shorthand for to_element_builder().build() if we want to simply take the default builder and not change anything.
        let stack = stack.to_element(0, ctx);

        // Now, we add the stack to the grid.
        grid.add(stack, 3, 0)?;

        // And finally build the grid.
        let grid = grid
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            .with_padding((24., 16., 16., 16.))
            .build();

        // The horizontal box is exactly the same as the vertical box except for orientation.
        // We will use a horizontal box to contain the boxes created so far.
        // if you don't want to create multiple variables, adding of children can be done inline for non-grid
        // containers by using .with_child.
        Ok(Self {
            gui: ui::containers::HorizontalBox::new()
                .to_element_builder(0, ctx)
                .with_child(ver_box)
                .with_child(grid)
                .build(),
        })
    }
source

pub fn with_trigger_sound( self, trigger_sound: impl Into<Option<Source>> ) -> Self

Sets a sound to be played whenever this element is triggered via key press or mouse click.

Examples found in repository?
examples/ui_examples/e_messages.rs (line 82)
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    pub fn new(ctx: &Context) -> GameResult<Self> {


        // This title will change based on transitions whenever certain buttons are clicked.
        let title = Text::new("Move this element with the buttons.\nYou have not yet clicked a button.")
        // First, we style the title.
        .set_font("Bahnschrift")
        .set_scale(28.)
        .to_owned()
        .to_element_builder(0, ctx)
        // Then, we add a message handler to the element.
        .with_message_handler(

            // The message handle receives a set of messages and a mutable transition vector.
        |messages,_,transitions| {
            let ids = [11,12,13,21,22,23,];

            // We check if any of the buttons that interest us were clicked in the last frame.
            for id in ids{
                for message in messages{
                    if *message == ui::UiMessage::<()>::Clicked(id){

                        // If yes, we add a new transition to the vector.
                        transitions.push_back(
                            // Transitions are initalized with the duration they should take to complete and augmented via the builder pattern.
                            ui::Transition::new(Duration::ZERO)
                            // Here, we add a new content that will replace the old text once the transition completes.
                            .with_new_content(Text::new(format!(
                                "Move this element with the buttons.\nYou clicked a button with id {}.",
                                id
                            ))
                            .set_font("Bahnschrift")
                            .set_scale(24.)
                            .to_owned())
                        )
                        
                    }
                }
            }
        })
        .build();

        // Define a general visual style to use for all buttons.
        let vis = ui::Visuals::new(
            Color::from_rgb(77, 109, 191),
            Color::from_rgb(55, 67, 87),
            2.,
            4.,
        );

        // Create a grid box to hold all buttons.
        let mut grid_box = ui::containers::GridBox::new(2, 3);

        // Now, we create 6 buttons to move the element to all possible vertical and horizontal alignments and add them to the grid.
        let vert_up = Text::new(" ^ ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(11, ctx)
            .with_visuals(vis) 
            // We can also set a sound to be played on click/key press
            .with_trigger_sound(ggez::audio::Source::new(ctx, "/blipSelect.wav").ok())
            .build();
        grid_box
            .add(vert_up, 0, 0)?;

        let vert_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(12, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_ce, 0, 1)?;

        let vert_do = Text::new(" v ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(13, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_do, 0, 2)?;

        let hor_up = Text::new(" < ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(21, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_up, 1, 0)?;

        let hor_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(22, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_ce, 1, 1)?;

        let hor_do = Text::new(" > ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(23, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_do, 1, 2)?;

        // The well-known back button will take us back to scene select.
        let back = Text::new("Back")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .as_fill()
            .build();

        
        // We create a general VBox to contain our UI
        // We can create Vertical and Horizontal Boxes with the 'spaced' constructor to set its spacing value.
        let gui_box = ui::containers::VerticalBox::new_spaced(6.)
        .to_element_builder(0, ctx)
        // We put the title, grid and back button together in a box.
        .with_child(title)
        .with_child(grid_box.to_element(30, ctx))
        .with_child(back)
        .with_size(ui::Size::Shrink(128., f32::INFINITY), ui::Size::Shrink(0., f32::INFINITY))
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(120, 170, 200),
            Color::from_rgb(55, 67, 87),
            2.,
            0.,
        ))
        // Another message handler. Along with the messages and transition vector as discussed above, we also receive a layout struct
        // that represents the layout struct of the element in the moment the transition was initialized. This allows us to only change
        // the relevant parts of the layout without having to recreate it from scratch.
        .with_message_handler(|messages, layout, transitions| {
            // This guards prevent spam clicking a button from locking up the element with 1.5-second transitions.
            if !transitions.is_empty() {
                return;
            }
            let vert_map = HashMap::from([
                (11, ui::Alignment::Min),
                (12, ui::Alignment::Center),
                (13, ui::Alignment::Max),
            ]);
            let hor_map = HashMap::from([
                (21, ui::Alignment::Min),
                (22, ui::Alignment::Center),
                (23, ui::Alignment::Max),
            ]);
            // Check if any vertical buttons were clicked.
            for (key, val) in vert_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        // If yes, add a transition.
                        ui::Transition::new(Duration::from_secs_f32(1.5))
                        // This time, we don't change the content, but the layout.
                        // Layout, visuals and hover_visuals are not  changed on completion like content, but instead applied gradually.
                        .with_new_layout(ui::Layout{
                            y_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
            // Repeat for horizontal keys.
            for (key, val) in hor_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        ui::Transition::new(Duration::from_secs_f32(1.5)).with_new_layout(ui::Layout{
                            x_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
        })
        .build();

        // Finally, we wrap our gui_box into a space-filling stack pane so we have a place to later add further elements

        Ok(Self {
            gui: ui::containers::StackBox::new()
            .to_element_builder(100, ctx)
            .as_fill()
            .with_child(gui_box)
            .build()
        })
    }
source

pub fn with_tooltip(self, tooltip: impl Into<Option<UiElement<T>>>) -> Self

Sets the elements tooltip to the specified UiContent (or disables any tooltip by passing None). Tooltips are displayed when hovering over an element with the mouse cursor. Most specific alignment and sizes of tooltips will be ignored. Tooltips will always be shrink in both dimensions and align as close to the cursor as possible.

Examples found in repository?
examples/ui_examples/g_selector_scene.rs (lines 48-60)
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Defining visuals

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        // Creating main grid

        let mut grid = ui::containers::GridBox::new(3, 2);

        let contents = ["Scene", "UiElement", "Container", "Messages", "Sprites"];

        for (i, &cont) in contents.iter().enumerate() {
            grid.add(
                graphics::Text::new(cont)
                    .set_scale(32.)
                    .to_owned()
                    .to_element_builder(i as u32 + 1, ctx)
                    .with_visuals(vis)
                    .with_hover_visuals(hover_vis)
                    .with_tooltip(
                        graphics::Text::new(format!(
                            "Click to look at the Scene created in the file {}.",
                            contents[i].to_lowercase()
                        ))
                        .set_scale(24.)
                        .set_wrap(true)
                        .set_bounds(glam::Vec2::new(240., 500.))
                        .to_owned()
                        .to_element_builder(0, ctx)
                        .with_visuals(hover_vis)
                        .build(),
                    )
                    .build(),
                i % 3,
                i / 3,
            )?;
        }

        // Add quit button

        grid.add(
            graphics::Text::new("Quit")
                .set_scale(32.)
                .to_owned()
                .to_element_builder(6, ctx)
                .with_visuals(vis)
                .with_hover_visuals(hover_vis)
                .build(),
            2,
            1,
        )?;

        Ok(Self {
            gui: grid.to_element_builder(0, ctx).build(),
        })
    }
More examples
Hide additional examples
examples/ui_examples/f_sprites.rs (lines 72-80)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Reusing the visuals from E.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            1.,
            0.,
        );

        // A sprite can be loaded by specifying a path, just like an Image.
        // Additionaly, you need to inform the sprite of the grid size of its sheet and the duration each frame is displayed.
        let ui_sprite = sprite::Sprite::from_path(
            "/moo-sheet_16_16.png",
            ctx,
            16,
            24,
            Duration::from_secs_f32(0.25),
        )?
        // Just like any UI element, a sprite can have visuals, tooltip, ect.
        .to_element_builder(1, ctx)
        .scaled(5., 5.)
        .with_visuals(vis)
        .with_hover_visuals(hover_vis)
        .with_tooltip(
            graphics::Text::new("This is a sprite! Click it to end the scene.")
                .set_scale(28.)
                .set_font("Bahnschrift")
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(cont_vis)
                .build(),
        )
        .as_shrink()
        .build();

        // Sprites can also be initiated from a sprite pool, to make repeated file system access unneccessary
        // and streamline loading of multiple sprites. This requires sprites in the folder to be formatted appropriately.

        let sprite_pool = sprite::SpritePool::new()
            // with_folder loads all .png/.bmp/.jpg/.jpeg files from the passed folder and optionally its subfolders
            .with_folder(ctx, "/", true);

        // We can now init a sprite from the pool. Sprites are saved in the pool with a key corresponding to their relative path
        // (from the resource folder) with the format information and file ending removed.
        let non_ui_sprite = sprite_pool.init_sprite("/mage-sheet", Duration::from_secs_f32(0.2))?;

        // you can also initialize a sprite pool without any folder at all
        let mut sprite_pool2 = sprite::SpritePool::new();

        // in this case, you can use lazy initialisation of sprites to fill the sprite pool only with those sprites currently needed.
        // Lazy initilisation draws from the pool if possible, from the file system if needed (and loads into the pool in this case) and panics if it can't find anything in the fs.
        // Requires a mutable sprite pool!
        // For testing purposes, we are loading a sprite we have already loaded - this should be drawn from the pool.
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/mage-sheet", Duration::from_secs_f32(0.5))?;
        // now load the correct sprite
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/moo-sheet", lazy_sprite.get_frame_time())?;

        Ok(Self {
            gui: ui_sprite,
            sprite: non_ui_sprite,
            sprite2: lazy_sprite,
            pos: Vec2::new(50., 200.),
            v: Vec2::new(4., 4.),
        })
    }
source

pub fn with_message_handler( self, handler: impl Fn(&HashSet<UiMessage<T>>, Layout, &mut VecDeque<Transition<T>>) + 'static ) -> Self

Sets the elements message handler. The message handler lambda receives each frame a hash set consisting of all internal and external messages received by this element. It also receives a function pointer. Calling this pointer with a transition pushes that transition to this elements transition queue. Lastly, it receives the current layout of the element. This allows any transitions to re-use that layout and only change the variables the transition wants to change.

Examples found in repository?
examples/ui_examples/e_messages.rs (lines 33-61)
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    pub fn new(ctx: &Context) -> GameResult<Self> {


        // This title will change based on transitions whenever certain buttons are clicked.
        let title = Text::new("Move this element with the buttons.\nYou have not yet clicked a button.")
        // First, we style the title.
        .set_font("Bahnschrift")
        .set_scale(28.)
        .to_owned()
        .to_element_builder(0, ctx)
        // Then, we add a message handler to the element.
        .with_message_handler(

            // The message handle receives a set of messages and a mutable transition vector.
        |messages,_,transitions| {
            let ids = [11,12,13,21,22,23,];

            // We check if any of the buttons that interest us were clicked in the last frame.
            for id in ids{
                for message in messages{
                    if *message == ui::UiMessage::<()>::Clicked(id){

                        // If yes, we add a new transition to the vector.
                        transitions.push_back(
                            // Transitions are initalized with the duration they should take to complete and augmented via the builder pattern.
                            ui::Transition::new(Duration::ZERO)
                            // Here, we add a new content that will replace the old text once the transition completes.
                            .with_new_content(Text::new(format!(
                                "Move this element with the buttons.\nYou clicked a button with id {}.",
                                id
                            ))
                            .set_font("Bahnschrift")
                            .set_scale(24.)
                            .to_owned())
                        )
                        
                    }
                }
            }
        })
        .build();

        // Define a general visual style to use for all buttons.
        let vis = ui::Visuals::new(
            Color::from_rgb(77, 109, 191),
            Color::from_rgb(55, 67, 87),
            2.,
            4.,
        );

        // Create a grid box to hold all buttons.
        let mut grid_box = ui::containers::GridBox::new(2, 3);

        // Now, we create 6 buttons to move the element to all possible vertical and horizontal alignments and add them to the grid.
        let vert_up = Text::new(" ^ ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(11, ctx)
            .with_visuals(vis) 
            // We can also set a sound to be played on click/key press
            .with_trigger_sound(ggez::audio::Source::new(ctx, "/blipSelect.wav").ok())
            .build();
        grid_box
            .add(vert_up, 0, 0)?;

        let vert_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(12, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_ce, 0, 1)?;

        let vert_do = Text::new(" v ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(13, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_do, 0, 2)?;

        let hor_up = Text::new(" < ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(21, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_up, 1, 0)?;

        let hor_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(22, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_ce, 1, 1)?;

        let hor_do = Text::new(" > ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(23, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_do, 1, 2)?;

        // The well-known back button will take us back to scene select.
        let back = Text::new("Back")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .as_fill()
            .build();

        
        // We create a general VBox to contain our UI
        // We can create Vertical and Horizontal Boxes with the 'spaced' constructor to set its spacing value.
        let gui_box = ui::containers::VerticalBox::new_spaced(6.)
        .to_element_builder(0, ctx)
        // We put the title, grid and back button together in a box.
        .with_child(title)
        .with_child(grid_box.to_element(30, ctx))
        .with_child(back)
        .with_size(ui::Size::Shrink(128., f32::INFINITY), ui::Size::Shrink(0., f32::INFINITY))
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(120, 170, 200),
            Color::from_rgb(55, 67, 87),
            2.,
            0.,
        ))
        // Another message handler. Along with the messages and transition vector as discussed above, we also receive a layout struct
        // that represents the layout struct of the element in the moment the transition was initialized. This allows us to only change
        // the relevant parts of the layout without having to recreate it from scratch.
        .with_message_handler(|messages, layout, transitions| {
            // This guards prevent spam clicking a button from locking up the element with 1.5-second transitions.
            if !transitions.is_empty() {
                return;
            }
            let vert_map = HashMap::from([
                (11, ui::Alignment::Min),
                (12, ui::Alignment::Center),
                (13, ui::Alignment::Max),
            ]);
            let hor_map = HashMap::from([
                (21, ui::Alignment::Min),
                (22, ui::Alignment::Center),
                (23, ui::Alignment::Max),
            ]);
            // Check if any vertical buttons were clicked.
            for (key, val) in vert_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        // If yes, add a transition.
                        ui::Transition::new(Duration::from_secs_f32(1.5))
                        // This time, we don't change the content, but the layout.
                        // Layout, visuals and hover_visuals are not  changed on completion like content, but instead applied gradually.
                        .with_new_layout(ui::Layout{
                            y_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
            // Repeat for horizontal keys.
            for (key, val) in hor_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        ui::Transition::new(Duration::from_secs_f32(1.5)).with_new_layout(ui::Layout{
                            x_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
        })
        .build();

        // Finally, we wrap our gui_box into a space-filling stack pane so we have a place to later add further elements

        Ok(Self {
            gui: ui::containers::StackBox::new()
            .to_element_builder(100, ctx)
            .as_fill()
            .with_child(gui_box)
            .build()
        })
    }
source

pub fn with_layout(self, layout: Layout) -> Self

Sets the elements entire layout.

source

pub fn with_offset( self, x_offset: impl Into<Option<f32>>, y_offset: impl Into<Option<f32>> ) -> Self

Sets only the offset values of the elements layout. Pass None in any argument to leave that offset as-is.

Examples found in repository?
examples/ui_examples/e_messages.rs (line 246)
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
    fn update(&mut self, ctx: &mut Context) -> Result<scene_manager::SceneSwitch, GameError> {
        // Nothing much to do here, except implement the back button functionality.

        let messages = self.gui.manage_messages(ctx, None);

        if messages.contains(&ui::UiMessage::Triggered(1)){
            // If it is, we end the current scene (and return to the previous one) by popping it off the stack.
            return Ok(scene_manager::SceneSwitch::pop(1));
        }

        if messages.contains(&ui::UiMessage::Triggered(13)){
            // If a certain button is pressed, add a small text element to the gui.
            self.gui.add_element(100,
                // using a duration box as a wrapper will remove the element after a set amount of time
                  ui::containers::DurationBox::new(
                    Duration::from_secs_f32(1.5),
                     graphics::Text::new("Just a small reminder that you pressed button 13.")
                     .set_font("Bahnschrift")
                     .set_wrap(true)
                     .set_bounds(glam::Vec2::new(200., 500.))
                     .set_scale(28.)
                     .to_owned()
                     .to_element_builder(0, ctx)
                     .with_visuals(ui::Visuals::new(
                        Color::from_rgb(77, 109, 191),
                        Color::from_rgb(55, 67, 87),
                        2.,
                        4.,
                    ))
                     .build()
                    ).to_element_builder(0, ctx)
                    .with_alignment(ui::Alignment::Center, ui::Alignment::Min)
                    .with_offset(0., 25.)
                    .build()
                    );
        }

        Ok(scene_manager::SceneSwitch::None)
    
    }
More examples
Hide additional examples
examples/ui_examples/c_uielement.rs (line 47)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    pub fn new(ctx: &Context) -> Self{
        // The scene constructor is usually the place where we create the state of our UI.
        // In this case, we will only create a single element.

        let text_element = 
        // First, we create anything implementing UiContent. ggez Image and Text do that, so we'll use a Text.
        // You can format that text as you can in ggez, so let's use our custom font and set a larger size.
        graphics::Text::new("Take me back!") 
        .set_font("Bahnschrift")
        .set_scale(32.)
        // Then we'll convert that content to an UiElementBuilder. We have to give it an ID.
        // ID 0 is reserved for elements not sending messages, but since we want to use the Text as a button, we'll use 1.
        .to_owned()
        .to_element_builder(1, ctx) 
        // We can now use the functions of UiElementBuilder to style and position our element.
        // First, we'll set the visuals using a Visuals struct.
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(49, 53, 69),
            Color::from_rgb(250, 246, 230),
            4.,8. 
        ))
        // Additionally, you can add keycodes that make your element respond to key presses as it would respond to clicks
        .with_trigger_key(winit::event::VirtualKeyCode::A)
        // We can also set the alignment within the window...
        .with_alignment(ui::Alignment::Min, ui::Alignment::Center)
        // ... offset the element (note that we can pass None into most of these functions to leave the presets for one dimension untouched) ...
        .with_offset(25., None)
        // ... or set its padding ...
        .with_padding((5., 10., 5., 10.))
        // ... and size. Here, we use a special method 'shrink' that sets the size of both dimension to shrink without changing their boundaries.
        // Using the function .with_size would require us to also pass in boundaries.
        .as_shrink()
        // Finally, we build the element.
        .build();

        Self{gui: text_element}
    }
examples/ui_examples/d_containers.rs (line 123)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Predefine some visuals so we don't have to do it for every element.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        // You can also create 'custom' visuals that allow you to set the thickness of each border & radius of each corner separately.

        let vis2 = ui::Visuals::new_custom(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            [4., 1., 4., 1.],
            [2., 2., 2., 2.],
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new_custom(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            [16., 8., 8., 8.],
            [12., 2., 2., 12.],
        );

        // Note that the constructor now returns a Result.
        // This is neccessary as the 'add' function used to add UI elements to grid containers can fail, thus failing the constructor.

        // The first container we use is a vertical box simply laying out elements from top to bottom.
        let mut ver_box = ui::containers::VerticalBox::new();
        // We can manually change the spacing between elements in the box
        ver_box.spacing = 10.;
        // first, we need to add all the children to this vertical box.
        // We'll just use TextElement for now, but these can also be images, sprites, placeholders or more containers.
        for i in 0..8 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis2)
                .build();
            // Add the element to the box. This cannot fail for non-grid containers, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox, it would simply consume the element and do nothing.
            ver_box.add(element);
        }
        // After adding all children, we can convert to a UiElement and style the box like we would style an other element. The usual pattern here is to shadow the variable to avoid use-after-move.
        let ver_box = ver_box
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            // Using larger padding to accomodate our thick borders.
            .with_padding((24., 16., 16., 16.))
            .build();

        // Another container we can use is GridBox. A GridBox needs to be initialized with a set height and width and cannot be extended.
        let mut grid = ui::containers::GridBox::new(4, 4);
        // The contents of a grid box are initialized as empty elements.  We'll add buttons to the diagonal of the grid.
        for i in 0..4 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis)
                // Elements can be given alignment and will align within their respecitive cell in the grid.
                .with_alignment(ui::Alignment::Max, None)
                .build();
            // Add the element to the box. This can fail, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox.
            grid.add(element, i, i)?;
        }

        // We'll also create our usual back button and put it into the top right of the grid.

        let back = graphics::Text::new("Back!")
            .set_font("Bahnschrift")
            .set_scale(28.)
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .with_hover_visuals(hover_vis)
            .build();

        // This time, we'll enhance our back button a bit by using an icon that is displayed over the top left corner.
        // To achieve this, we'll use a StackBox.
        let mut stack = ui::containers::StackBox::new();
        stack.add(back);
        // The add_top function adds something to the top of a stack box. Creating and adding an element can be done inline.
        stack.add_top(
            graphics::Image::from_path(ctx, "/moo.png")?
                .to_element_builder(0, ctx)
                // We'll align the icon to the top right
                .with_alignment(ui::Alignment::Min, ui::Alignment::Min)
                // and offset it slightly
                .with_offset(-10., -10.)
                .build(),
        )?;
        // to_element is a shorthand for to_element_builder().build() if we want to simply take the default builder and not change anything.
        let stack = stack.to_element(0, ctx);

        // Now, we add the stack to the grid.
        grid.add(stack, 3, 0)?;

        // And finally build the grid.
        let grid = grid
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            .with_padding((24., 16., 16., 16.))
            .build();

        // The horizontal box is exactly the same as the vertical box except for orientation.
        // We will use a horizontal box to contain the boxes created so far.
        // if you don't want to create multiple variables, adding of children can be done inline for non-grid
        // containers by using .with_child.
        Ok(Self {
            gui: ui::containers::HorizontalBox::new()
                .to_element_builder(0, ctx)
                .with_child(ver_box)
                .with_child(grid)
                .build(),
        })
    }
source

pub fn with_alignment( self, x_alignment: impl Into<Option<Alignment>>, y_alignment: impl Into<Option<Alignment>> ) -> Self

Sets only the alingment of the elements layout. Pass None in any argument to leave that alignment as-is.

Examples found in repository?
examples/ui_examples/e_messages.rs (line 245)
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
    fn update(&mut self, ctx: &mut Context) -> Result<scene_manager::SceneSwitch, GameError> {
        // Nothing much to do here, except implement the back button functionality.

        let messages = self.gui.manage_messages(ctx, None);

        if messages.contains(&ui::UiMessage::Triggered(1)){
            // If it is, we end the current scene (and return to the previous one) by popping it off the stack.
            return Ok(scene_manager::SceneSwitch::pop(1));
        }

        if messages.contains(&ui::UiMessage::Triggered(13)){
            // If a certain button is pressed, add a small text element to the gui.
            self.gui.add_element(100,
                // using a duration box as a wrapper will remove the element after a set amount of time
                  ui::containers::DurationBox::new(
                    Duration::from_secs_f32(1.5),
                     graphics::Text::new("Just a small reminder that you pressed button 13.")
                     .set_font("Bahnschrift")
                     .set_wrap(true)
                     .set_bounds(glam::Vec2::new(200., 500.))
                     .set_scale(28.)
                     .to_owned()
                     .to_element_builder(0, ctx)
                     .with_visuals(ui::Visuals::new(
                        Color::from_rgb(77, 109, 191),
                        Color::from_rgb(55, 67, 87),
                        2.,
                        4.,
                    ))
                     .build()
                    ).to_element_builder(0, ctx)
                    .with_alignment(ui::Alignment::Center, ui::Alignment::Min)
                    .with_offset(0., 25.)
                    .build()
                    );
        }

        Ok(scene_manager::SceneSwitch::None)
    
    }
More examples
Hide additional examples
examples/ui_examples/c_uielement.rs (line 45)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    pub fn new(ctx: &Context) -> Self{
        // The scene constructor is usually the place where we create the state of our UI.
        // In this case, we will only create a single element.

        let text_element = 
        // First, we create anything implementing UiContent. ggez Image and Text do that, so we'll use a Text.
        // You can format that text as you can in ggez, so let's use our custom font and set a larger size.
        graphics::Text::new("Take me back!") 
        .set_font("Bahnschrift")
        .set_scale(32.)
        // Then we'll convert that content to an UiElementBuilder. We have to give it an ID.
        // ID 0 is reserved for elements not sending messages, but since we want to use the Text as a button, we'll use 1.
        .to_owned()
        .to_element_builder(1, ctx) 
        // We can now use the functions of UiElementBuilder to style and position our element.
        // First, we'll set the visuals using a Visuals struct.
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(49, 53, 69),
            Color::from_rgb(250, 246, 230),
            4.,8. 
        ))
        // Additionally, you can add keycodes that make your element respond to key presses as it would respond to clicks
        .with_trigger_key(winit::event::VirtualKeyCode::A)
        // We can also set the alignment within the window...
        .with_alignment(ui::Alignment::Min, ui::Alignment::Center)
        // ... offset the element (note that we can pass None into most of these functions to leave the presets for one dimension untouched) ...
        .with_offset(25., None)
        // ... or set its padding ...
        .with_padding((5., 10., 5., 10.))
        // ... and size. Here, we use a special method 'shrink' that sets the size of both dimension to shrink without changing their boundaries.
        // Using the function .with_size would require us to also pass in boundaries.
        .as_shrink()
        // Finally, we build the element.
        .build();

        Self{gui: text_element}
    }
examples/ui_examples/d_containers.rs (line 94)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Predefine some visuals so we don't have to do it for every element.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        // You can also create 'custom' visuals that allow you to set the thickness of each border & radius of each corner separately.

        let vis2 = ui::Visuals::new_custom(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            [4., 1., 4., 1.],
            [2., 2., 2., 2.],
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new_custom(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            [16., 8., 8., 8.],
            [12., 2., 2., 12.],
        );

        // Note that the constructor now returns a Result.
        // This is neccessary as the 'add' function used to add UI elements to grid containers can fail, thus failing the constructor.

        // The first container we use is a vertical box simply laying out elements from top to bottom.
        let mut ver_box = ui::containers::VerticalBox::new();
        // We can manually change the spacing between elements in the box
        ver_box.spacing = 10.;
        // first, we need to add all the children to this vertical box.
        // We'll just use TextElement for now, but these can also be images, sprites, placeholders or more containers.
        for i in 0..8 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis2)
                .build();
            // Add the element to the box. This cannot fail for non-grid containers, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox, it would simply consume the element and do nothing.
            ver_box.add(element);
        }
        // After adding all children, we can convert to a UiElement and style the box like we would style an other element. The usual pattern here is to shadow the variable to avoid use-after-move.
        let ver_box = ver_box
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            // Using larger padding to accomodate our thick borders.
            .with_padding((24., 16., 16., 16.))
            .build();

        // Another container we can use is GridBox. A GridBox needs to be initialized with a set height and width and cannot be extended.
        let mut grid = ui::containers::GridBox::new(4, 4);
        // The contents of a grid box are initialized as empty elements.  We'll add buttons to the diagonal of the grid.
        for i in 0..4 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis)
                // Elements can be given alignment and will align within their respecitive cell in the grid.
                .with_alignment(ui::Alignment::Max, None)
                .build();
            // Add the element to the box. This can fail, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox.
            grid.add(element, i, i)?;
        }

        // We'll also create our usual back button and put it into the top right of the grid.

        let back = graphics::Text::new("Back!")
            .set_font("Bahnschrift")
            .set_scale(28.)
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .with_hover_visuals(hover_vis)
            .build();

        // This time, we'll enhance our back button a bit by using an icon that is displayed over the top left corner.
        // To achieve this, we'll use a StackBox.
        let mut stack = ui::containers::StackBox::new();
        stack.add(back);
        // The add_top function adds something to the top of a stack box. Creating and adding an element can be done inline.
        stack.add_top(
            graphics::Image::from_path(ctx, "/moo.png")?
                .to_element_builder(0, ctx)
                // We'll align the icon to the top right
                .with_alignment(ui::Alignment::Min, ui::Alignment::Min)
                // and offset it slightly
                .with_offset(-10., -10.)
                .build(),
        )?;
        // to_element is a shorthand for to_element_builder().build() if we want to simply take the default builder and not change anything.
        let stack = stack.to_element(0, ctx);

        // Now, we add the stack to the grid.
        grid.add(stack, 3, 0)?;

        // And finally build the grid.
        let grid = grid
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            .with_padding((24., 16., 16., 16.))
            .build();

        // The horizontal box is exactly the same as the vertical box except for orientation.
        // We will use a horizontal box to contain the boxes created so far.
        // if you don't want to create multiple variables, adding of children can be done inline for non-grid
        // containers by using .with_child.
        Ok(Self {
            gui: ui::containers::HorizontalBox::new()
                .to_element_builder(0, ctx)
                .with_child(ver_box)
                .with_child(grid)
                .build(),
        })
    }
source

pub fn with_trigger_key(self, key: VirtualKeyCode) -> Self

Attaches a key code to this element. Pressing this key will send the same trigger event as clicking the element.

Examples found in repository?
examples/ui_examples/c_uielement.rs (line 43)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    pub fn new(ctx: &Context) -> Self{
        // The scene constructor is usually the place where we create the state of our UI.
        // In this case, we will only create a single element.

        let text_element = 
        // First, we create anything implementing UiContent. ggez Image and Text do that, so we'll use a Text.
        // You can format that text as you can in ggez, so let's use our custom font and set a larger size.
        graphics::Text::new("Take me back!") 
        .set_font("Bahnschrift")
        .set_scale(32.)
        // Then we'll convert that content to an UiElementBuilder. We have to give it an ID.
        // ID 0 is reserved for elements not sending messages, but since we want to use the Text as a button, we'll use 1.
        .to_owned()
        .to_element_builder(1, ctx) 
        // We can now use the functions of UiElementBuilder to style and position our element.
        // First, we'll set the visuals using a Visuals struct.
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(49, 53, 69),
            Color::from_rgb(250, 246, 230),
            4.,8. 
        ))
        // Additionally, you can add keycodes that make your element respond to key presses as it would respond to clicks
        .with_trigger_key(winit::event::VirtualKeyCode::A)
        // We can also set the alignment within the window...
        .with_alignment(ui::Alignment::Min, ui::Alignment::Center)
        // ... offset the element (note that we can pass None into most of these functions to leave the presets for one dimension untouched) ...
        .with_offset(25., None)
        // ... or set its padding ...
        .with_padding((5., 10., 5., 10.))
        // ... and size. Here, we use a special method 'shrink' that sets the size of both dimension to shrink without changing their boundaries.
        // Using the function .with_size would require us to also pass in boundaries.
        .as_shrink()
        // Finally, we build the element.
        .build();

        Self{gui: text_element}
    }
source

pub fn with_padding(self, padding: (f32, f32, f32, f32)) -> Self

Sets only the padding of the elements layout.

Examples found in repository?
examples/ui_examples/c_uielement.rs (line 49)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    pub fn new(ctx: &Context) -> Self{
        // The scene constructor is usually the place where we create the state of our UI.
        // In this case, we will only create a single element.

        let text_element = 
        // First, we create anything implementing UiContent. ggez Image and Text do that, so we'll use a Text.
        // You can format that text as you can in ggez, so let's use our custom font and set a larger size.
        graphics::Text::new("Take me back!") 
        .set_font("Bahnschrift")
        .set_scale(32.)
        // Then we'll convert that content to an UiElementBuilder. We have to give it an ID.
        // ID 0 is reserved for elements not sending messages, but since we want to use the Text as a button, we'll use 1.
        .to_owned()
        .to_element_builder(1, ctx) 
        // We can now use the functions of UiElementBuilder to style and position our element.
        // First, we'll set the visuals using a Visuals struct.
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(49, 53, 69),
            Color::from_rgb(250, 246, 230),
            4.,8. 
        ))
        // Additionally, you can add keycodes that make your element respond to key presses as it would respond to clicks
        .with_trigger_key(winit::event::VirtualKeyCode::A)
        // We can also set the alignment within the window...
        .with_alignment(ui::Alignment::Min, ui::Alignment::Center)
        // ... offset the element (note that we can pass None into most of these functions to leave the presets for one dimension untouched) ...
        .with_offset(25., None)
        // ... or set its padding ...
        .with_padding((5., 10., 5., 10.))
        // ... and size. Here, we use a special method 'shrink' that sets the size of both dimension to shrink without changing their boundaries.
        // Using the function .with_size would require us to also pass in boundaries.
        .as_shrink()
        // Finally, we build the element.
        .build();

        Self{gui: text_element}
    }
More examples
Hide additional examples
examples/ui_examples/d_containers.rs (line 79)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Predefine some visuals so we don't have to do it for every element.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        // You can also create 'custom' visuals that allow you to set the thickness of each border & radius of each corner separately.

        let vis2 = ui::Visuals::new_custom(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            [4., 1., 4., 1.],
            [2., 2., 2., 2.],
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new_custom(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            [16., 8., 8., 8.],
            [12., 2., 2., 12.],
        );

        // Note that the constructor now returns a Result.
        // This is neccessary as the 'add' function used to add UI elements to grid containers can fail, thus failing the constructor.

        // The first container we use is a vertical box simply laying out elements from top to bottom.
        let mut ver_box = ui::containers::VerticalBox::new();
        // We can manually change the spacing between elements in the box
        ver_box.spacing = 10.;
        // first, we need to add all the children to this vertical box.
        // We'll just use TextElement for now, but these can also be images, sprites, placeholders or more containers.
        for i in 0..8 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis2)
                .build();
            // Add the element to the box. This cannot fail for non-grid containers, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox, it would simply consume the element and do nothing.
            ver_box.add(element);
        }
        // After adding all children, we can convert to a UiElement and style the box like we would style an other element. The usual pattern here is to shadow the variable to avoid use-after-move.
        let ver_box = ver_box
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            // Using larger padding to accomodate our thick borders.
            .with_padding((24., 16., 16., 16.))
            .build();

        // Another container we can use is GridBox. A GridBox needs to be initialized with a set height and width and cannot be extended.
        let mut grid = ui::containers::GridBox::new(4, 4);
        // The contents of a grid box are initialized as empty elements.  We'll add buttons to the diagonal of the grid.
        for i in 0..4 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis)
                // Elements can be given alignment and will align within their respecitive cell in the grid.
                .with_alignment(ui::Alignment::Max, None)
                .build();
            // Add the element to the box. This can fail, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox.
            grid.add(element, i, i)?;
        }

        // We'll also create our usual back button and put it into the top right of the grid.

        let back = graphics::Text::new("Back!")
            .set_font("Bahnschrift")
            .set_scale(28.)
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .with_hover_visuals(hover_vis)
            .build();

        // This time, we'll enhance our back button a bit by using an icon that is displayed over the top left corner.
        // To achieve this, we'll use a StackBox.
        let mut stack = ui::containers::StackBox::new();
        stack.add(back);
        // The add_top function adds something to the top of a stack box. Creating and adding an element can be done inline.
        stack.add_top(
            graphics::Image::from_path(ctx, "/moo.png")?
                .to_element_builder(0, ctx)
                // We'll align the icon to the top right
                .with_alignment(ui::Alignment::Min, ui::Alignment::Min)
                // and offset it slightly
                .with_offset(-10., -10.)
                .build(),
        )?;
        // to_element is a shorthand for to_element_builder().build() if we want to simply take the default builder and not change anything.
        let stack = stack.to_element(0, ctx);

        // Now, we add the stack to the grid.
        grid.add(stack, 3, 0)?;

        // And finally build the grid.
        let grid = grid
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            .with_padding((24., 16., 16., 16.))
            .build();

        // The horizontal box is exactly the same as the vertical box except for orientation.
        // We will use a horizontal box to contain the boxes created so far.
        // if you don't want to create multiple variables, adding of children can be done inline for non-grid
        // containers by using .with_child.
        Ok(Self {
            gui: ui::containers::HorizontalBox::new()
                .to_element_builder(0, ctx)
                .with_child(ver_box)
                .with_child(grid)
                .build(),
        })
    }
source

pub fn with_preserve_ratio(self, preserve_ratio: bool) -> Self

Sets only the presever_ratio parameter of the elements layout.

source

pub fn with_size( self, x_size: impl Into<Option<Size>>, y_size: impl Into<Option<Size>> ) -> Self

Sets only the size of the elements layout. Pass None in any argument to leave that size as-is.

Examples found in repository?
examples/ui_examples/e_messages.rs (line 146)
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    pub fn new(ctx: &Context) -> GameResult<Self> {


        // This title will change based on transitions whenever certain buttons are clicked.
        let title = Text::new("Move this element with the buttons.\nYou have not yet clicked a button.")
        // First, we style the title.
        .set_font("Bahnschrift")
        .set_scale(28.)
        .to_owned()
        .to_element_builder(0, ctx)
        // Then, we add a message handler to the element.
        .with_message_handler(

            // The message handle receives a set of messages and a mutable transition vector.
        |messages,_,transitions| {
            let ids = [11,12,13,21,22,23,];

            // We check if any of the buttons that interest us were clicked in the last frame.
            for id in ids{
                for message in messages{
                    if *message == ui::UiMessage::<()>::Clicked(id){

                        // If yes, we add a new transition to the vector.
                        transitions.push_back(
                            // Transitions are initalized with the duration they should take to complete and augmented via the builder pattern.
                            ui::Transition::new(Duration::ZERO)
                            // Here, we add a new content that will replace the old text once the transition completes.
                            .with_new_content(Text::new(format!(
                                "Move this element with the buttons.\nYou clicked a button with id {}.",
                                id
                            ))
                            .set_font("Bahnschrift")
                            .set_scale(24.)
                            .to_owned())
                        )
                        
                    }
                }
            }
        })
        .build();

        // Define a general visual style to use for all buttons.
        let vis = ui::Visuals::new(
            Color::from_rgb(77, 109, 191),
            Color::from_rgb(55, 67, 87),
            2.,
            4.,
        );

        // Create a grid box to hold all buttons.
        let mut grid_box = ui::containers::GridBox::new(2, 3);

        // Now, we create 6 buttons to move the element to all possible vertical and horizontal alignments and add them to the grid.
        let vert_up = Text::new(" ^ ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(11, ctx)
            .with_visuals(vis) 
            // We can also set a sound to be played on click/key press
            .with_trigger_sound(ggez::audio::Source::new(ctx, "/blipSelect.wav").ok())
            .build();
        grid_box
            .add(vert_up, 0, 0)?;

        let vert_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(12, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_ce, 0, 1)?;

        let vert_do = Text::new(" v ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(13, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_do, 0, 2)?;

        let hor_up = Text::new(" < ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(21, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_up, 1, 0)?;

        let hor_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(22, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_ce, 1, 1)?;

        let hor_do = Text::new(" > ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(23, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_do, 1, 2)?;

        // The well-known back button will take us back to scene select.
        let back = Text::new("Back")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .as_fill()
            .build();

        
        // We create a general VBox to contain our UI
        // We can create Vertical and Horizontal Boxes with the 'spaced' constructor to set its spacing value.
        let gui_box = ui::containers::VerticalBox::new_spaced(6.)
        .to_element_builder(0, ctx)
        // We put the title, grid and back button together in a box.
        .with_child(title)
        .with_child(grid_box.to_element(30, ctx))
        .with_child(back)
        .with_size(ui::Size::Shrink(128., f32::INFINITY), ui::Size::Shrink(0., f32::INFINITY))
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(120, 170, 200),
            Color::from_rgb(55, 67, 87),
            2.,
            0.,
        ))
        // Another message handler. Along with the messages and transition vector as discussed above, we also receive a layout struct
        // that represents the layout struct of the element in the moment the transition was initialized. This allows us to only change
        // the relevant parts of the layout without having to recreate it from scratch.
        .with_message_handler(|messages, layout, transitions| {
            // This guards prevent spam clicking a button from locking up the element with 1.5-second transitions.
            if !transitions.is_empty() {
                return;
            }
            let vert_map = HashMap::from([
                (11, ui::Alignment::Min),
                (12, ui::Alignment::Center),
                (13, ui::Alignment::Max),
            ]);
            let hor_map = HashMap::from([
                (21, ui::Alignment::Min),
                (22, ui::Alignment::Center),
                (23, ui::Alignment::Max),
            ]);
            // Check if any vertical buttons were clicked.
            for (key, val) in vert_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        // If yes, add a transition.
                        ui::Transition::new(Duration::from_secs_f32(1.5))
                        // This time, we don't change the content, but the layout.
                        // Layout, visuals and hover_visuals are not  changed on completion like content, but instead applied gradually.
                        .with_new_layout(ui::Layout{
                            y_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
            // Repeat for horizontal keys.
            for (key, val) in hor_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        ui::Transition::new(Duration::from_secs_f32(1.5)).with_new_layout(ui::Layout{
                            x_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
        })
        .build();

        // Finally, we wrap our gui_box into a space-filling stack pane so we have a place to later add further elements

        Ok(Self {
            gui: ui::containers::StackBox::new()
            .to_element_builder(100, ctx)
            .as_fill()
            .with_child(gui_box)
            .build()
        })
    }
source

pub fn as_shrink(self) -> Self

Changes both sizes of the element to SHRINK, taking any boundaries from previous size.

Examples found in repository?
examples/ui_examples/c_uielement.rs (line 52)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    pub fn new(ctx: &Context) -> Self{
        // The scene constructor is usually the place where we create the state of our UI.
        // In this case, we will only create a single element.

        let text_element = 
        // First, we create anything implementing UiContent. ggez Image and Text do that, so we'll use a Text.
        // You can format that text as you can in ggez, so let's use our custom font and set a larger size.
        graphics::Text::new("Take me back!") 
        .set_font("Bahnschrift")
        .set_scale(32.)
        // Then we'll convert that content to an UiElementBuilder. We have to give it an ID.
        // ID 0 is reserved for elements not sending messages, but since we want to use the Text as a button, we'll use 1.
        .to_owned()
        .to_element_builder(1, ctx) 
        // We can now use the functions of UiElementBuilder to style and position our element.
        // First, we'll set the visuals using a Visuals struct.
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(49, 53, 69),
            Color::from_rgb(250, 246, 230),
            4.,8. 
        ))
        // Additionally, you can add keycodes that make your element respond to key presses as it would respond to clicks
        .with_trigger_key(winit::event::VirtualKeyCode::A)
        // We can also set the alignment within the window...
        .with_alignment(ui::Alignment::Min, ui::Alignment::Center)
        // ... offset the element (note that we can pass None into most of these functions to leave the presets for one dimension untouched) ...
        .with_offset(25., None)
        // ... or set its padding ...
        .with_padding((5., 10., 5., 10.))
        // ... and size. Here, we use a special method 'shrink' that sets the size of both dimension to shrink without changing their boundaries.
        // Using the function .with_size would require us to also pass in boundaries.
        .as_shrink()
        // Finally, we build the element.
        .build();

        Self{gui: text_element}
    }
More examples
Hide additional examples
examples/ui_examples/f_sprites.rs (line 81)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Reusing the visuals from E.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            1.,
            0.,
        );

        // A sprite can be loaded by specifying a path, just like an Image.
        // Additionaly, you need to inform the sprite of the grid size of its sheet and the duration each frame is displayed.
        let ui_sprite = sprite::Sprite::from_path(
            "/moo-sheet_16_16.png",
            ctx,
            16,
            24,
            Duration::from_secs_f32(0.25),
        )?
        // Just like any UI element, a sprite can have visuals, tooltip, ect.
        .to_element_builder(1, ctx)
        .scaled(5., 5.)
        .with_visuals(vis)
        .with_hover_visuals(hover_vis)
        .with_tooltip(
            graphics::Text::new("This is a sprite! Click it to end the scene.")
                .set_scale(28.)
                .set_font("Bahnschrift")
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(cont_vis)
                .build(),
        )
        .as_shrink()
        .build();

        // Sprites can also be initiated from a sprite pool, to make repeated file system access unneccessary
        // and streamline loading of multiple sprites. This requires sprites in the folder to be formatted appropriately.

        let sprite_pool = sprite::SpritePool::new()
            // with_folder loads all .png/.bmp/.jpg/.jpeg files from the passed folder and optionally its subfolders
            .with_folder(ctx, "/", true);

        // We can now init a sprite from the pool. Sprites are saved in the pool with a key corresponding to their relative path
        // (from the resource folder) with the format information and file ending removed.
        let non_ui_sprite = sprite_pool.init_sprite("/mage-sheet", Duration::from_secs_f32(0.2))?;

        // you can also initialize a sprite pool without any folder at all
        let mut sprite_pool2 = sprite::SpritePool::new();

        // in this case, you can use lazy initialisation of sprites to fill the sprite pool only with those sprites currently needed.
        // Lazy initilisation draws from the pool if possible, from the file system if needed (and loads into the pool in this case) and panics if it can't find anything in the fs.
        // Requires a mutable sprite pool!
        // For testing purposes, we are loading a sprite we have already loaded - this should be drawn from the pool.
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/mage-sheet", Duration::from_secs_f32(0.5))?;
        // now load the correct sprite
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/moo-sheet", lazy_sprite.get_frame_time())?;

        Ok(Self {
            gui: ui_sprite,
            sprite: non_ui_sprite,
            sprite2: lazy_sprite,
            pos: Vec2::new(50., 200.),
            v: Vec2::new(4., 4.),
        })
    }
source

pub fn as_fill(self) -> Self

Changes both sizes of the element to FILL, taking any boundaries from previous size.

Examples found in repository?
examples/ui_examples/e_messages.rs (line 134)
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    pub fn new(ctx: &Context) -> GameResult<Self> {


        // This title will change based on transitions whenever certain buttons are clicked.
        let title = Text::new("Move this element with the buttons.\nYou have not yet clicked a button.")
        // First, we style the title.
        .set_font("Bahnschrift")
        .set_scale(28.)
        .to_owned()
        .to_element_builder(0, ctx)
        // Then, we add a message handler to the element.
        .with_message_handler(

            // The message handle receives a set of messages and a mutable transition vector.
        |messages,_,transitions| {
            let ids = [11,12,13,21,22,23,];

            // We check if any of the buttons that interest us were clicked in the last frame.
            for id in ids{
                for message in messages{
                    if *message == ui::UiMessage::<()>::Clicked(id){

                        // If yes, we add a new transition to the vector.
                        transitions.push_back(
                            // Transitions are initalized with the duration they should take to complete and augmented via the builder pattern.
                            ui::Transition::new(Duration::ZERO)
                            // Here, we add a new content that will replace the old text once the transition completes.
                            .with_new_content(Text::new(format!(
                                "Move this element with the buttons.\nYou clicked a button with id {}.",
                                id
                            ))
                            .set_font("Bahnschrift")
                            .set_scale(24.)
                            .to_owned())
                        )
                        
                    }
                }
            }
        })
        .build();

        // Define a general visual style to use for all buttons.
        let vis = ui::Visuals::new(
            Color::from_rgb(77, 109, 191),
            Color::from_rgb(55, 67, 87),
            2.,
            4.,
        );

        // Create a grid box to hold all buttons.
        let mut grid_box = ui::containers::GridBox::new(2, 3);

        // Now, we create 6 buttons to move the element to all possible vertical and horizontal alignments and add them to the grid.
        let vert_up = Text::new(" ^ ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(11, ctx)
            .with_visuals(vis) 
            // We can also set a sound to be played on click/key press
            .with_trigger_sound(ggez::audio::Source::new(ctx, "/blipSelect.wav").ok())
            .build();
        grid_box
            .add(vert_up, 0, 0)?;

        let vert_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(12, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_ce, 0, 1)?;

        let vert_do = Text::new(" v ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(13, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_do, 0, 2)?;

        let hor_up = Text::new(" < ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(21, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_up, 1, 0)?;

        let hor_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(22, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_ce, 1, 1)?;

        let hor_do = Text::new(" > ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(23, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_do, 1, 2)?;

        // The well-known back button will take us back to scene select.
        let back = Text::new("Back")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .as_fill()
            .build();

        
        // We create a general VBox to contain our UI
        // We can create Vertical and Horizontal Boxes with the 'spaced' constructor to set its spacing value.
        let gui_box = ui::containers::VerticalBox::new_spaced(6.)
        .to_element_builder(0, ctx)
        // We put the title, grid and back button together in a box.
        .with_child(title)
        .with_child(grid_box.to_element(30, ctx))
        .with_child(back)
        .with_size(ui::Size::Shrink(128., f32::INFINITY), ui::Size::Shrink(0., f32::INFINITY))
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(120, 170, 200),
            Color::from_rgb(55, 67, 87),
            2.,
            0.,
        ))
        // Another message handler. Along with the messages and transition vector as discussed above, we also receive a layout struct
        // that represents the layout struct of the element in the moment the transition was initialized. This allows us to only change
        // the relevant parts of the layout without having to recreate it from scratch.
        .with_message_handler(|messages, layout, transitions| {
            // This guards prevent spam clicking a button from locking up the element with 1.5-second transitions.
            if !transitions.is_empty() {
                return;
            }
            let vert_map = HashMap::from([
                (11, ui::Alignment::Min),
                (12, ui::Alignment::Center),
                (13, ui::Alignment::Max),
            ]);
            let hor_map = HashMap::from([
                (21, ui::Alignment::Min),
                (22, ui::Alignment::Center),
                (23, ui::Alignment::Max),
            ]);
            // Check if any vertical buttons were clicked.
            for (key, val) in vert_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        // If yes, add a transition.
                        ui::Transition::new(Duration::from_secs_f32(1.5))
                        // This time, we don't change the content, but the layout.
                        // Layout, visuals and hover_visuals are not  changed on completion like content, but instead applied gradually.
                        .with_new_layout(ui::Layout{
                            y_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
            // Repeat for horizontal keys.
            for (key, val) in hor_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        ui::Transition::new(Duration::from_secs_f32(1.5)).with_new_layout(ui::Layout{
                            x_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
        })
        .build();

        // Finally, we wrap our gui_box into a space-filling stack pane so we have a place to later add further elements

        Ok(Self {
            gui: ui::containers::StackBox::new()
            .to_element_builder(100, ctx)
            .as_fill()
            .with_child(gui_box)
            .build()
        })
    }
source

pub fn scaled( self, x_scale: impl Into<Option<f32>>, y_scale: impl Into<Option<f32>> ) -> Self

Scales any boundaries of the sizes of this element by the respective factor. Pass in None or 1. to not scale any dimension.

Examples found in repository?
examples/ui_examples/f_sprites.rs (line 69)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Reusing the visuals from E.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            1.,
            0.,
        );

        // A sprite can be loaded by specifying a path, just like an Image.
        // Additionaly, you need to inform the sprite of the grid size of its sheet and the duration each frame is displayed.
        let ui_sprite = sprite::Sprite::from_path(
            "/moo-sheet_16_16.png",
            ctx,
            16,
            24,
            Duration::from_secs_f32(0.25),
        )?
        // Just like any UI element, a sprite can have visuals, tooltip, ect.
        .to_element_builder(1, ctx)
        .scaled(5., 5.)
        .with_visuals(vis)
        .with_hover_visuals(hover_vis)
        .with_tooltip(
            graphics::Text::new("This is a sprite! Click it to end the scene.")
                .set_scale(28.)
                .set_font("Bahnschrift")
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(cont_vis)
                .build(),
        )
        .as_shrink()
        .build();

        // Sprites can also be initiated from a sprite pool, to make repeated file system access unneccessary
        // and streamline loading of multiple sprites. This requires sprites in the folder to be formatted appropriately.

        let sprite_pool = sprite::SpritePool::new()
            // with_folder loads all .png/.bmp/.jpg/.jpeg files from the passed folder and optionally its subfolders
            .with_folder(ctx, "/", true);

        // We can now init a sprite from the pool. Sprites are saved in the pool with a key corresponding to their relative path
        // (from the resource folder) with the format information and file ending removed.
        let non_ui_sprite = sprite_pool.init_sprite("/mage-sheet", Duration::from_secs_f32(0.2))?;

        // you can also initialize a sprite pool without any folder at all
        let mut sprite_pool2 = sprite::SpritePool::new();

        // in this case, you can use lazy initialisation of sprites to fill the sprite pool only with those sprites currently needed.
        // Lazy initilisation draws from the pool if possible, from the file system if needed (and loads into the pool in this case) and panics if it can't find anything in the fs.
        // Requires a mutable sprite pool!
        // For testing purposes, we are loading a sprite we have already loaded - this should be drawn from the pool.
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/mage-sheet", Duration::from_secs_f32(0.5))?;
        // now load the correct sprite
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/moo-sheet", lazy_sprite.get_frame_time())?;

        Ok(Self {
            gui: ui_sprite,
            sprite: non_ui_sprite,
            sprite2: lazy_sprite,
            pos: Vec2::new(50., 200.),
            v: Vec2::new(4., 4.),
        })
    }
source

pub fn with_wrapper_layout(self, wrapped_layout: Layout) -> Self

Takes in a layout and sets the elements layout to be as you would want for a container wrapping the passed layout. Sets size to fill, taking boundaries from the passed layout + padding, and own padding to 0.

source

pub fn build(self) -> UiElement<T>

Returns the underlying built element.

Examples found in repository?
examples/ui_examples/c_uielement.rs (line 54)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    pub fn new(ctx: &Context) -> Self{
        // The scene constructor is usually the place where we create the state of our UI.
        // In this case, we will only create a single element.

        let text_element = 
        // First, we create anything implementing UiContent. ggez Image and Text do that, so we'll use a Text.
        // You can format that text as you can in ggez, so let's use our custom font and set a larger size.
        graphics::Text::new("Take me back!") 
        .set_font("Bahnschrift")
        .set_scale(32.)
        // Then we'll convert that content to an UiElementBuilder. We have to give it an ID.
        // ID 0 is reserved for elements not sending messages, but since we want to use the Text as a button, we'll use 1.
        .to_owned()
        .to_element_builder(1, ctx) 
        // We can now use the functions of UiElementBuilder to style and position our element.
        // First, we'll set the visuals using a Visuals struct.
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(49, 53, 69),
            Color::from_rgb(250, 246, 230),
            4.,8. 
        ))
        // Additionally, you can add keycodes that make your element respond to key presses as it would respond to clicks
        .with_trigger_key(winit::event::VirtualKeyCode::A)
        // We can also set the alignment within the window...
        .with_alignment(ui::Alignment::Min, ui::Alignment::Center)
        // ... offset the element (note that we can pass None into most of these functions to leave the presets for one dimension untouched) ...
        .with_offset(25., None)
        // ... or set its padding ...
        .with_padding((5., 10., 5., 10.))
        // ... and size. Here, we use a special method 'shrink' that sets the size of both dimension to shrink without changing their boundaries.
        // Using the function .with_size would require us to also pass in boundaries.
        .as_shrink()
        // Finally, we build the element.
        .build();

        Self{gui: text_element}
    }
More examples
Hide additional examples
examples/ui_examples/g_selector_scene.rs (line 59)
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Defining visuals

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        // Creating main grid

        let mut grid = ui::containers::GridBox::new(3, 2);

        let contents = ["Scene", "UiElement", "Container", "Messages", "Sprites"];

        for (i, &cont) in contents.iter().enumerate() {
            grid.add(
                graphics::Text::new(cont)
                    .set_scale(32.)
                    .to_owned()
                    .to_element_builder(i as u32 + 1, ctx)
                    .with_visuals(vis)
                    .with_hover_visuals(hover_vis)
                    .with_tooltip(
                        graphics::Text::new(format!(
                            "Click to look at the Scene created in the file {}.",
                            contents[i].to_lowercase()
                        ))
                        .set_scale(24.)
                        .set_wrap(true)
                        .set_bounds(glam::Vec2::new(240., 500.))
                        .to_owned()
                        .to_element_builder(0, ctx)
                        .with_visuals(hover_vis)
                        .build(),
                    )
                    .build(),
                i % 3,
                i / 3,
            )?;
        }

        // Add quit button

        grid.add(
            graphics::Text::new("Quit")
                .set_scale(32.)
                .to_owned()
                .to_element_builder(6, ctx)
                .with_visuals(vis)
                .with_hover_visuals(hover_vis)
                .build(),
            2,
            1,
        )?;

        Ok(Self {
            gui: grid.to_element_builder(0, ctx).build(),
        })
    }
examples/ui_examples/f_sprites.rs (line 79)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Reusing the visuals from E.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            1.,
            0.,
        );

        // A sprite can be loaded by specifying a path, just like an Image.
        // Additionaly, you need to inform the sprite of the grid size of its sheet and the duration each frame is displayed.
        let ui_sprite = sprite::Sprite::from_path(
            "/moo-sheet_16_16.png",
            ctx,
            16,
            24,
            Duration::from_secs_f32(0.25),
        )?
        // Just like any UI element, a sprite can have visuals, tooltip, ect.
        .to_element_builder(1, ctx)
        .scaled(5., 5.)
        .with_visuals(vis)
        .with_hover_visuals(hover_vis)
        .with_tooltip(
            graphics::Text::new("This is a sprite! Click it to end the scene.")
                .set_scale(28.)
                .set_font("Bahnschrift")
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(cont_vis)
                .build(),
        )
        .as_shrink()
        .build();

        // Sprites can also be initiated from a sprite pool, to make repeated file system access unneccessary
        // and streamline loading of multiple sprites. This requires sprites in the folder to be formatted appropriately.

        let sprite_pool = sprite::SpritePool::new()
            // with_folder loads all .png/.bmp/.jpg/.jpeg files from the passed folder and optionally its subfolders
            .with_folder(ctx, "/", true);

        // We can now init a sprite from the pool. Sprites are saved in the pool with a key corresponding to their relative path
        // (from the resource folder) with the format information and file ending removed.
        let non_ui_sprite = sprite_pool.init_sprite("/mage-sheet", Duration::from_secs_f32(0.2))?;

        // you can also initialize a sprite pool without any folder at all
        let mut sprite_pool2 = sprite::SpritePool::new();

        // in this case, you can use lazy initialisation of sprites to fill the sprite pool only with those sprites currently needed.
        // Lazy initilisation draws from the pool if possible, from the file system if needed (and loads into the pool in this case) and panics if it can't find anything in the fs.
        // Requires a mutable sprite pool!
        // For testing purposes, we are loading a sprite we have already loaded - this should be drawn from the pool.
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/mage-sheet", Duration::from_secs_f32(0.5))?;
        // now load the correct sprite
        let lazy_sprite =
            sprite_pool2.init_sprite_lazy(ctx, "/moo-sheet", lazy_sprite.get_frame_time())?;

        Ok(Self {
            gui: ui_sprite,
            sprite: non_ui_sprite,
            sprite2: lazy_sprite,
            pos: Vec2::new(50., 200.),
            v: Vec2::new(4., 4.),
        })
    }
examples/ui_examples/d_containers.rs (line 69)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    pub fn new(ctx: &Context) -> Result<Self, GameError> {
        // Predefine some visuals so we don't have to do it for every element.

        let vis = ui::Visuals::new(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            1.,
            0.,
        );

        // You can also create 'custom' visuals that allow you to set the thickness of each border & radius of each corner separately.

        let vis2 = ui::Visuals::new_custom(
            Color::from_rgb(180, 120, 60),
            Color::from_rgb(18, 12, 6),
            [4., 1., 4., 1.],
            [2., 2., 2., 2.],
        );

        let hover_vis = ui::Visuals::new(
            Color::from_rgb(160, 100, 40),
            Color::from_rgb(18, 12, 6),
            3.,
            0.,
        );

        let cont_vis = ui::Visuals::new_custom(
            Color::from_rgb(60, 120, 180),
            Color::from_rgb(180, 180, 190),
            [16., 8., 8., 8.],
            [12., 2., 2., 12.],
        );

        // Note that the constructor now returns a Result.
        // This is neccessary as the 'add' function used to add UI elements to grid containers can fail, thus failing the constructor.

        // The first container we use is a vertical box simply laying out elements from top to bottom.
        let mut ver_box = ui::containers::VerticalBox::new();
        // We can manually change the spacing between elements in the box
        ver_box.spacing = 10.;
        // first, we need to add all the children to this vertical box.
        // We'll just use TextElement for now, but these can also be images, sprites, placeholders or more containers.
        for i in 0..8 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis2)
                .build();
            // Add the element to the box. This cannot fail for non-grid containers, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox, it would simply consume the element and do nothing.
            ver_box.add(element);
        }
        // After adding all children, we can convert to a UiElement and style the box like we would style an other element. The usual pattern here is to shadow the variable to avoid use-after-move.
        let ver_box = ver_box
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            // Using larger padding to accomodate our thick borders.
            .with_padding((24., 16., 16., 16.))
            .build();

        // Another container we can use is GridBox. A GridBox needs to be initialized with a set height and width and cannot be extended.
        let mut grid = ui::containers::GridBox::new(4, 4);
        // The contents of a grid box are initialized as empty elements.  We'll add buttons to the diagonal of the grid.
        for i in 0..4 {
            // Create an element.
            let element = graphics::Text::new(format!("{}", i))
                .set_font("Bahnschrift")
                .set_scale(28.)
                .to_owned()
                .to_element_builder(0, ctx)
                .with_visuals(vis)
                // Elements can be given alignment and will align within their respecitive cell in the grid.
                .with_alignment(ui::Alignment::Max, None)
                .build();
            // Add the element to the box. This can fail, if ver_box were not an actual container
            // or a container that requires a special method for adding, like e.g. GridBox.
            grid.add(element, i, i)?;
        }

        // We'll also create our usual back button and put it into the top right of the grid.

        let back = graphics::Text::new("Back!")
            .set_font("Bahnschrift")
            .set_scale(28.)
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .with_hover_visuals(hover_vis)
            .build();

        // This time, we'll enhance our back button a bit by using an icon that is displayed over the top left corner.
        // To achieve this, we'll use a StackBox.
        let mut stack = ui::containers::StackBox::new();
        stack.add(back);
        // The add_top function adds something to the top of a stack box. Creating and adding an element can be done inline.
        stack.add_top(
            graphics::Image::from_path(ctx, "/moo.png")?
                .to_element_builder(0, ctx)
                // We'll align the icon to the top right
                .with_alignment(ui::Alignment::Min, ui::Alignment::Min)
                // and offset it slightly
                .with_offset(-10., -10.)
                .build(),
        )?;
        // to_element is a shorthand for to_element_builder().build() if we want to simply take the default builder and not change anything.
        let stack = stack.to_element(0, ctx);

        // Now, we add the stack to the grid.
        grid.add(stack, 3, 0)?;

        // And finally build the grid.
        let grid = grid
            .to_element_builder(0, ctx)
            .with_visuals(cont_vis)
            .with_padding((24., 16., 16., 16.))
            .build();

        // The horizontal box is exactly the same as the vertical box except for orientation.
        // We will use a horizontal box to contain the boxes created so far.
        // if you don't want to create multiple variables, adding of children can be done inline for non-grid
        // containers by using .with_child.
        Ok(Self {
            gui: ui::containers::HorizontalBox::new()
                .to_element_builder(0, ctx)
                .with_child(ver_box)
                .with_child(grid)
                .build(),
        })
    }
examples/ui_examples/e_messages.rs (line 62)
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
    pub fn new(ctx: &Context) -> GameResult<Self> {


        // This title will change based on transitions whenever certain buttons are clicked.
        let title = Text::new("Move this element with the buttons.\nYou have not yet clicked a button.")
        // First, we style the title.
        .set_font("Bahnschrift")
        .set_scale(28.)
        .to_owned()
        .to_element_builder(0, ctx)
        // Then, we add a message handler to the element.
        .with_message_handler(

            // The message handle receives a set of messages and a mutable transition vector.
        |messages,_,transitions| {
            let ids = [11,12,13,21,22,23,];

            // We check if any of the buttons that interest us were clicked in the last frame.
            for id in ids{
                for message in messages{
                    if *message == ui::UiMessage::<()>::Clicked(id){

                        // If yes, we add a new transition to the vector.
                        transitions.push_back(
                            // Transitions are initalized with the duration they should take to complete and augmented via the builder pattern.
                            ui::Transition::new(Duration::ZERO)
                            // Here, we add a new content that will replace the old text once the transition completes.
                            .with_new_content(Text::new(format!(
                                "Move this element with the buttons.\nYou clicked a button with id {}.",
                                id
                            ))
                            .set_font("Bahnschrift")
                            .set_scale(24.)
                            .to_owned())
                        )
                        
                    }
                }
            }
        })
        .build();

        // Define a general visual style to use for all buttons.
        let vis = ui::Visuals::new(
            Color::from_rgb(77, 109, 191),
            Color::from_rgb(55, 67, 87),
            2.,
            4.,
        );

        // Create a grid box to hold all buttons.
        let mut grid_box = ui::containers::GridBox::new(2, 3);

        // Now, we create 6 buttons to move the element to all possible vertical and horizontal alignments and add them to the grid.
        let vert_up = Text::new(" ^ ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(11, ctx)
            .with_visuals(vis) 
            // We can also set a sound to be played on click/key press
            .with_trigger_sound(ggez::audio::Source::new(ctx, "/blipSelect.wav").ok())
            .build();
        grid_box
            .add(vert_up, 0, 0)?;

        let vert_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(12, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_ce, 0, 1)?;

        let vert_do = Text::new(" v ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(13, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(vert_do, 0, 2)?;

        let hor_up = Text::new(" < ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(21, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_up, 1, 0)?;

        let hor_ce = Text::new(" . ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(22, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_ce, 1, 1)?;

        let hor_do = Text::new(" > ")
            .set_font("Bahnschrift")
            .to_owned().to_element_builder(23, ctx)
            .with_visuals(vis)
            .build();
        grid_box
            .add(hor_do, 1, 2)?;

        // The well-known back button will take us back to scene select.
        let back = Text::new("Back")
            .set_font("Bahnschrift")
            .to_owned()
            .to_element_builder(1, ctx)
            .with_visuals(vis)
            .as_fill()
            .build();

        
        // We create a general VBox to contain our UI
        // We can create Vertical and Horizontal Boxes with the 'spaced' constructor to set its spacing value.
        let gui_box = ui::containers::VerticalBox::new_spaced(6.)
        .to_element_builder(0, ctx)
        // We put the title, grid and back button together in a box.
        .with_child(title)
        .with_child(grid_box.to_element(30, ctx))
        .with_child(back)
        .with_size(ui::Size::Shrink(128., f32::INFINITY), ui::Size::Shrink(0., f32::INFINITY))
        .with_visuals(ui::Visuals::new(
            Color::from_rgb(120, 170, 200),
            Color::from_rgb(55, 67, 87),
            2.,
            0.,
        ))
        // Another message handler. Along with the messages and transition vector as discussed above, we also receive a layout struct
        // that represents the layout struct of the element in the moment the transition was initialized. This allows us to only change
        // the relevant parts of the layout without having to recreate it from scratch.
        .with_message_handler(|messages, layout, transitions| {
            // This guards prevent spam clicking a button from locking up the element with 1.5-second transitions.
            if !transitions.is_empty() {
                return;
            }
            let vert_map = HashMap::from([
                (11, ui::Alignment::Min),
                (12, ui::Alignment::Center),
                (13, ui::Alignment::Max),
            ]);
            let hor_map = HashMap::from([
                (21, ui::Alignment::Min),
                (22, ui::Alignment::Center),
                (23, ui::Alignment::Max),
            ]);
            // Check if any vertical buttons were clicked.
            for (key, val) in vert_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        // If yes, add a transition.
                        ui::Transition::new(Duration::from_secs_f32(1.5))
                        // This time, we don't change the content, but the layout.
                        // Layout, visuals and hover_visuals are not  changed on completion like content, but instead applied gradually.
                        .with_new_layout(ui::Layout{
                            y_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
            // Repeat for horizontal keys.
            for (key, val) in hor_map {
                if messages.contains(&ui::UiMessage::Triggered(key)) {
                    transitions.push_back(
                        ui::Transition::new(Duration::from_secs_f32(1.5)).with_new_layout(ui::Layout{
                            x_alignment: val,
                            ..layout
                        }),
                    );
                }
            }
        })
        .build();

        // Finally, we wrap our gui_box into a space-filling stack pane so we have a place to later add further elements

        Ok(Self {
            gui: ui::containers::StackBox::new()
            .to_element_builder(100, ctx)
            .as_fill()
            .with_child(gui_box)
            .build()
        })
    }
}


impl scene_manager::Scene for EScene {
    fn update(&mut self, ctx: &mut Context) -> Result<scene_manager::SceneSwitch, GameError> {
        // Nothing much to do here, except implement the back button functionality.

        let messages = self.gui.manage_messages(ctx, None);

        if messages.contains(&ui::UiMessage::Triggered(1)){
            // If it is, we end the current scene (and return to the previous one) by popping it off the stack.
            return Ok(scene_manager::SceneSwitch::pop(1));
        }

        if messages.contains(&ui::UiMessage::Triggered(13)){
            // If a certain button is pressed, add a small text element to the gui.
            self.gui.add_element(100,
                // using a duration box as a wrapper will remove the element after a set amount of time
                  ui::containers::DurationBox::new(
                    Duration::from_secs_f32(1.5),
                     graphics::Text::new("Just a small reminder that you pressed button 13.")
                     .set_font("Bahnschrift")
                     .set_wrap(true)
                     .set_bounds(glam::Vec2::new(200., 500.))
                     .set_scale(28.)
                     .to_owned()
                     .to_element_builder(0, ctx)
                     .with_visuals(ui::Visuals::new(
                        Color::from_rgb(77, 109, 191),
                        Color::from_rgb(55, 67, 87),
                        2.,
                        4.,
                    ))
                     .build()
                    ).to_element_builder(0, ctx)
                    .with_alignment(ui::Alignment::Center, ui::Alignment::Min)
                    .with_offset(0., 25.)
                    .build()
                    );
        }

        Ok(scene_manager::SceneSwitch::None)
    
    }

Trait Implementations§

source§

impl<T: Debug + Copy + Eq + Hash> Debug for UiElementBuilder<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T: Copy + Eq + Hash> From<UiElement<T>> for UiElementBuilder<T>

source§

fn from(value: UiElement<T>) -> Self

Converts to this type from the input type.
source§

impl<T: Copy + Eq + Hash> From<UiElementBuilder<T>> for UiElement<T>

source§

fn from(value: UiElementBuilder<T>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for UiElementBuilder<T>

§

impl<T> !Send for UiElementBuilder<T>

§

impl<T> !Sync for UiElementBuilder<T>

§

impl<T> Unpin for UiElementBuilder<T>

§

impl<T> !UnwindSafe for UiElementBuilder<T>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<S> FromSample<S> for S

§

fn from_sample_(s: S) -> S

source§

impl<T> Has<T> for T

source§

fn retrieve(&self) -> &T

Method to retrieve the context type.
source§

impl<T> HasMut<T> for T

source§

fn retrieve_mut(&mut self) -> &mut T

Method to retrieve the context type as mutable.
source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<F, T> IntoSample<T> for Fwhere T: FromSample<F>,

§

fn into_sample(self) -> T

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T, U> ToSample<U> for Twhere U: FromSample<T>,

§

fn to_sample_(self) -> U

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<S, T> Duplex<S> for Twhere T: FromSample<S> + ToSample<S>,