Trait mooeye::ui::UiContent

source ·
pub trait UiContent<T: Copy + Eq + Hash> {
    // Required method
    fn draw_content(
        &mut self,
        ctx: &mut Context,
        canvas: &mut Canvas,
        param: UiDrawParam
    );

    // Provided methods
    fn to_element_builder(self, id: u32, _ctx: &Context) -> UiElementBuilder<T>
       where Self: Sized + 'static { ... }
    fn to_element(self, id: u32, ctx: &Context) -> UiElement<T>
       where Self: Sized + 'static { ... }
    fn expired(&self) -> bool { ... }
    fn container(&self) -> Option<&dyn UiContainer<T>> { ... }
    fn container_mut(&mut self) -> Option<&mut dyn UiContainer<T>> { ... }
}
Expand description

A trait that marks any struct that can be the content of a UI element. Should not be used directly, only when wrapped in such an element.

Basic elements

For basic elements, most default implementations will suffice, and only UiContent::draw_content needs to be implemented. If your element has special default layout requirements, you can overwrite the UiContent::to_element_builder constructor function.

Required Methods§

source

fn draw_content( &mut self, ctx: &mut Context, canvas: &mut Canvas, param: UiDrawParam )

Takes in a rectangle target, a canvas, a context and draws the contents (not the border etc.) to that rectangle within that canvas using that context. Normally, this will only be called from within private functions, when the cache has been modified appropiately and only use the inner rectangle of the draw cache as content_bounds. Do not call otherwise.

Provided Methods§

source

fn to_element_builder(self, id: u32, _ctx: &Context) -> UiElementBuilder<T>where Self: Sized + 'static,

Wraps the content into a UiElementBuilder and returns the builder. Use ID 0 iff you do not want this element to send any messages by itself. Overwrite this if your element should use special defaults. Context may be passed in if some elements (image element, text element) need to use context to measure themselves.

Examples found in repository?
examples/ui_examples/c_uielement.rs (line 34)
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 45)
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 68)
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 67)
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 31)
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

fn to_element(self, id: u32, ctx: &Context) -> UiElement<T>where Self: Sized + 'static,

A shorthand for creating an element builder and immediately building an element. Useful only if you do not want to diverge from any default layouts/visuals.

Examples found in repository?
examples/ui_examples/d_containers.rs (line 127)
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 144)
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

fn expired(&self) -> bool

Returns a bool value. Returning true indicates to any container this element is a child of that this element wishes to be removed from the container (and discarded).

source

fn container(&self) -> Option<&dyn UiContainer<T>>

Returns an immutable reference to Self (cast to a container) if this element also implements UiContainer. If it does not, returns None. Remember to overwrite this function for all of your custom containers!

source

fn container_mut(&mut self) -> Option<&mut dyn UiContainer<T>>

Returns a mutable reference to Self (cast to a container) if this element also implements UiContainer. If it does not, returns None. Remember to overwrite this function for all of your custom containers!

Implementations on Foreign Types§

source§

impl<T: Copy + Eq + Hash> UiContent<T> for ()

source§

fn to_element_builder(self, id: u32, _ctx: &Context) -> UiElementBuilder<T>where Self: Sized + 'static,

source§

fn draw_content( &mut self, _ctx: &mut Context, _canvas: &mut Canvas, _param: UiDrawParam )

source§

impl<T: Copy + Eq + Hash> UiContent<T> for Image

source§

fn to_element_builder(self, id: u32, ctx: &Context) -> UiElementBuilder<T>where Self: Sized + 'static,

source§

fn draw_content( &mut self, ctx: &mut Context, canvas: &mut Canvas, param: UiDrawParam )

source§

impl<T: Copy + Eq + Hash> UiContent<T> for Text

source§

fn to_element_builder(self, id: u32, ctx: &Context) -> UiElementBuilder<T>where Self: Sized + 'static,

source§

fn draw_content( &mut self, ctx: &mut Context, canvas: &mut Canvas, param: UiDrawParam )

Implementors§

source§

impl<T: Copy + Eq + Hash> UiContent<T> for Sprite

source§

impl<T: Copy + Eq + Hash> UiContent<T> for DurationBox<T>

source§

impl<T: Copy + Eq + Hash> UiContent<T> for GridBox<T>

source§

impl<T: Copy + Eq + Hash> UiContent<T> for HorizontalBox<T>

source§

impl<T: Copy + Eq + Hash> UiContent<T> for StackBox<T>

source§

impl<T: Copy + Eq + Hash> UiContent<T> for VerticalBox<T>