Skip to main content

ImageNode

Struct ImageNode 

Source
pub struct ImageNode {
    pub color: Color,
    pub image: Handle<Image>,
    pub texture_atlas: Option<TextureAtlas>,
    pub flip_x: bool,
    pub flip_y: bool,
    pub rect: Option<Rect>,
    pub image_mode: NodeImageMode,
    pub visual_box: VisualBox,
}
Expand description

A UI Node that renders an image.

Fields§

§color: Color

The tint color used to draw the image.

This is multiplied by the color of each pixel in the image. The field value defaults to solid white, which will pass the image through unmodified.

§image: Handle<Image>

Handle to the texture.

This defaults to a TRANSPARENT_IMAGE_HANDLE, which points to a fully transparent 1x1 texture.

§texture_atlas: Option<TextureAtlas>

The (optional) texture atlas used to render the image.

§flip_x: bool

Whether the image should be flipped along its x-axis.

§flip_y: bool

Whether the image should be flipped along its y-axis.

§rect: Option<Rect>

An optional rectangle representing the region of the image to render, instead of rendering the full image. This is an easy one-off alternative to using a TextureAtlas.

When used with a TextureAtlas, the rect is offset by the atlas’s minimal (top-left) corner position.

§image_mode: NodeImageMode

Controls how the image is altered to fit within the layout and how the layout algorithm determines the space to allocate for the image.

§visual_box: VisualBox

Which region of the UI node the image should be drawn within.

Implementations§

Source§

impl ImageNode

Source

pub fn new(texture: Handle<Image>) -> ImageNode

Create a new ImageNode with the given texture.

Examples found in repository?
examples/ui/scroll_and_overflow/overflow_debug.rs (line 143)
136fn spawn_image(
137    parent: &mut ChildSpawnerCommands,
138    asset_server: &Res<AssetServer>,
139    update_transform: impl UpdateTransform + Component,
140) {
141    spawn_container(parent, update_transform, |parent| {
142        parent.spawn((
143            ImageNode::new(asset_server.load("branding/bevy_logo_dark_big.png")),
144            Node {
145                height: px(100),
146                position_type: PositionType::Absolute,
147                top: px(-50),
148                left: px(-200),
149                ..default()
150            },
151        ));
152    });
153}
More examples
Hide additional examples
examples/ui/text/font_atlas_debug.rs (line 54)
39fn atlas_render_system(
40    mut commands: Commands,
41    mut state: ResMut<State>,
42    font_atlas_set: Res<FontAtlasSet>,
43    images: Res<Assets<Image>>,
44) {
45    if let Some(font_atlases) = font_atlas_set.values().next() {
46        let x_offset = state.atlas_count as f32;
47        if state.atlas_count == font_atlases.len() as u32 {
48            return;
49        }
50        let font_atlas = &font_atlases[state.atlas_count as usize];
51        let image = images.get(&font_atlas.texture).unwrap();
52        state.atlas_count += 1;
53        commands.spawn((
54            ImageNode::new(font_atlas.texture.clone()),
55            Node {
56                position_type: PositionType::Absolute,
57                top: Val::ZERO,
58                left: px(image.width() as f32 * x_offset),
59                ..default()
60            },
61        ));
62    }
63}
examples/showcase/game_menu.rs (line 89)
74    fn splash_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
75        let icon = asset_server.load("branding/icon.png");
76        // Display the logo
77        commands.spawn((
78            // This entity will be despawned when exiting the state
79            DespawnOnExit(GameState::Splash),
80            Node {
81                align_items: AlignItems::Center,
82                justify_content: JustifyContent::Center,
83                width: percent(100),
84                height: percent(100),
85                ..default()
86            },
87            OnSplashScreen,
88            children![(
89                ImageNode::new(icon),
90                Node {
91                    // This will set the logo to be 200px wide, and auto adjust its height
92                    width: px(200),
93                    ..default()
94                },
95            )],
96        ));
97        // Insert the timer as a resource
98        commands.insert_resource(SplashTimer(Timer::from_seconds(1.0, TimerMode::Once)));
99    }
100
101    // Tick the timer, and change state when finished
102    fn countdown(
103        mut game_state: ResMut<NextState<GameState>>,
104        time: Res<Time>,
105        mut timer: ResMut<SplashTimer>,
106    ) {
107        if timer.tick(time.delta()).is_finished() {
108            game_state.set(GameState::Menu);
109        }
110    }
111}
112
113mod game {
114    use bevy::{
115        color::palettes::basic::{BLUE, LIME},
116        prelude::*,
117    };
118
119    use super::{DisplayQuality, GameState, Volume, TEXT_COLOR};
120
121    // This plugin will contain the game. In this case, it's just be a screen that will
122    // display the current settings for 5 seconds before returning to the menu
123    pub fn game_plugin(app: &mut App) {
124        app.add_systems(OnEnter(GameState::Game), game_setup)
125            .add_systems(Update, game.run_if(in_state(GameState::Game)));
126    }
127
128    // Tag component used to tag entities added on the game screen
129    #[derive(Component)]
130    struct OnGameScreen;
131
132    #[derive(Resource, Deref, DerefMut)]
133    struct GameTimer(Timer);
134
135    fn game_setup(
136        mut commands: Commands,
137        display_quality: Res<DisplayQuality>,
138        volume: Res<Volume>,
139    ) {
140        commands.spawn((
141            DespawnOnExit(GameState::Game),
142            Node {
143                width: percent(100),
144                height: percent(100),
145                // center children
146                align_items: AlignItems::Center,
147                justify_content: JustifyContent::Center,
148                ..default()
149            },
150            OnGameScreen,
151            children![(
152                Node {
153                    // This will display its children in a column, from top to bottom
154                    flex_direction: FlexDirection::Column,
155                    // `align_items` will align children on the cross axis. Here the main axis is
156                    // vertical (column), so the cross axis is horizontal. This will center the
157                    // children
158                    align_items: AlignItems::Center,
159                    ..default()
160                },
161                BackgroundColor(Color::BLACK),
162                children![
163                    (
164                        Text::new("Will be back to the menu shortly..."),
165                        TextFont {
166                            font_size: FontSize::Px(67.0),
167                            ..default()
168                        },
169                        TextColor(TEXT_COLOR),
170                        Node {
171                            margin: UiRect::all(px(50)),
172                            ..default()
173                        },
174                    ),
175                    (
176                        Text::default(),
177                        Node {
178                            margin: UiRect::all(px(50)),
179                            ..default()
180                        },
181                        children![
182                            (
183                                TextSpan(format!("quality: {:?}", *display_quality)),
184                                TextFont {
185                                    font_size: FontSize::Px(50.0),
186                                    ..default()
187                                },
188                                TextColor(BLUE.into()),
189                            ),
190                            (
191                                TextSpan::new(" - "),
192                                TextFont {
193                                    font_size: FontSize::Px(50.0),
194                                    ..default()
195                                },
196                                TextColor(TEXT_COLOR),
197                            ),
198                            (
199                                TextSpan(format!("volume: {:?}", *volume)),
200                                TextFont {
201                                    font_size: FontSize::Px(50.0),
202                                    ..default()
203                                },
204                                TextColor(LIME.into()),
205                            ),
206                        ]
207                    ),
208                ]
209            )],
210        ));
211        // Spawn a 5 seconds timer to trigger going back to the menu
212        commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once)));
213    }
214
215    // Tick the timer, and change state when finished
216    fn game(
217        time: Res<Time>,
218        mut game_state: ResMut<NextState<GameState>>,
219        mut timer: ResMut<GameTimer>,
220    ) {
221        if timer.tick(time.delta()).is_finished() {
222            game_state.set(GameState::Menu);
223        }
224    }
225}
226
227mod menu {
228    use bevy::{
229        app::AppExit,
230        color::palettes::css::CRIMSON,
231        ecs::component::Mutable,
232        ecs::spawn::{SpawnIter, SpawnWith},
233        prelude::*,
234    };
235
236    use super::{DisplayQuality, GameState, Setting, Volume, TEXT_COLOR};
237
238    // This plugin manages the menu, with 5 different screens:
239    // - a main menu with "New Game", "Settings", "Quit"
240    // - a settings menu with two submenus and a back button
241    // - two settings screen with a setting that can be set and a back button
242    pub fn menu_plugin(app: &mut App) {
243        app
244            // At start, the menu is not enabled. This will be changed in `menu_setup` when
245            // entering the `GameState::Menu` state.
246            // Current screen in the menu is handled by an independent state from `GameState`
247            .init_state::<MenuState>()
248            .add_systems(OnEnter(GameState::Menu), menu_setup)
249            // Systems to handle the main menu screen
250            .add_systems(OnEnter(MenuState::Main), main_menu_setup)
251            // Systems to handle the settings menu screen
252            .add_systems(OnEnter(MenuState::Settings), settings_menu_setup)
253            // Systems to handle the display settings screen
254            .add_systems(
255                OnEnter(MenuState::SettingsDisplay),
256                display_settings_menu_setup,
257            )
258            .add_systems(
259                Update,
260                (setting_button::<DisplayQuality>.run_if(in_state(MenuState::SettingsDisplay)),),
261            )
262            // Systems to handle the sound settings screen
263            .add_systems(OnEnter(MenuState::SettingsSound), sound_settings_menu_setup)
264            .add_systems(
265                Update,
266                setting_button::<Volume>.run_if(in_state(MenuState::SettingsSound)),
267            )
268            // Common systems to all screens that handles buttons behavior
269            .add_systems(
270                Update,
271                (menu_action, button_system).run_if(in_state(GameState::Menu)),
272            );
273    }
274
275    // State used for the current menu screen
276    #[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
277    enum MenuState {
278        Main,
279        Settings,
280        SettingsDisplay,
281        SettingsSound,
282        #[default]
283        Disabled,
284    }
285
286    // Tag component used to tag entities added on the main menu screen
287    #[derive(Component)]
288    struct OnMainMenuScreen;
289
290    // Tag component used to tag entities added on the settings menu screen
291    #[derive(Component)]
292    struct OnSettingsMenuScreen;
293
294    // Tag component used to tag entities added on the display settings menu screen
295    #[derive(Component)]
296    struct OnDisplaySettingsMenuScreen;
297
298    // Tag component used to tag entities added on the sound settings menu screen
299    #[derive(Component)]
300    struct OnSoundSettingsMenuScreen;
301
302    const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
303    const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
304    const HOVERED_PRESSED_BUTTON: Color = Color::srgb(0.25, 0.65, 0.25);
305    const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
306
307    // Tag component used to mark which setting is currently selected
308    #[derive(Component)]
309    struct SelectedOption;
310
311    // All actions that can be triggered from a button click
312    #[derive(Component)]
313    enum MenuButtonAction {
314        Play,
315        Settings,
316        SettingsDisplay,
317        SettingsSound,
318        BackToMainMenu,
319        BackToSettings,
320        Quit,
321    }
322
323    // This system handles changing all buttons color based on mouse interaction
324    fn button_system(
325        mut interaction_query: Query<
326            (&Interaction, &mut BackgroundColor, Option<&SelectedOption>),
327            (Changed<Interaction>, With<Button>),
328        >,
329    ) {
330        for (interaction, mut background_color, selected) in &mut interaction_query {
331            *background_color = match (*interaction, selected) {
332                (Interaction::Pressed, _) | (Interaction::None, Some(_)) => PRESSED_BUTTON.into(),
333                (Interaction::Hovered, Some(_)) => HOVERED_PRESSED_BUTTON.into(),
334                (Interaction::Hovered, None) => HOVERED_BUTTON.into(),
335                (Interaction::None, None) => NORMAL_BUTTON.into(),
336            }
337        }
338    }
339
340    // This system updates the settings when a new value for a setting is selected, and marks
341    // the button as the one currently selected
342    fn setting_button<T: Resource<Mutability = Mutable> + Component + PartialEq + Copy>(
343        interaction_query: Query<
344            (&Interaction, &Setting<T>, Entity),
345            (Changed<Interaction>, With<Button>),
346        >,
347        selected_query: Single<(Entity, &mut BackgroundColor), With<SelectedOption>>,
348        mut commands: Commands,
349        mut setting: ResMut<T>,
350    ) {
351        let (previous_button, mut previous_button_color) = selected_query.into_inner();
352        for (interaction, button_setting, entity) in &interaction_query {
353            if *interaction == Interaction::Pressed && *setting != button_setting.0 {
354                *previous_button_color = NORMAL_BUTTON.into();
355                commands.entity(previous_button).remove::<SelectedOption>();
356                commands.entity(entity).insert(SelectedOption);
357                *setting = button_setting.0;
358            }
359        }
360    }
361
362    fn menu_setup(mut menu_state: ResMut<NextState<MenuState>>) {
363        menu_state.set(MenuState::Main);
364    }
365
366    fn main_menu_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
367        // Common style for all buttons on the screen
368        let button_node = Node {
369            width: px(300),
370            height: px(65),
371            margin: UiRect::all(px(20)),
372            justify_content: JustifyContent::Center,
373            align_items: AlignItems::Center,
374            ..default()
375        };
376        let button_icon_node = Node {
377            width: px(30),
378            // This takes the icons out of the flexbox flow, to be positioned exactly
379            position_type: PositionType::Absolute,
380            // The icon will be close to the left border of the button
381            left: px(10),
382            ..default()
383        };
384        let button_text_font = TextFont {
385            font_size: FontSize::Px(33.0),
386            ..default()
387        };
388
389        let right_icon = asset_server.load("textures/Game Icons/right.png");
390        let wrench_icon = asset_server.load("textures/Game Icons/wrench.png");
391        let exit_icon = asset_server.load("textures/Game Icons/exitRight.png");
392
393        commands.spawn((
394            DespawnOnExit(MenuState::Main),
395            Node {
396                width: percent(100),
397                height: percent(100),
398                align_items: AlignItems::Center,
399                justify_content: JustifyContent::Center,
400                ..default()
401            },
402            OnMainMenuScreen,
403            children![(
404                Node {
405                    flex_direction: FlexDirection::Column,
406                    align_items: AlignItems::Center,
407                    ..default()
408                },
409                BackgroundColor(CRIMSON.into()),
410                children![
411                    // Display the game name
412                    (
413                        Text::new("Bevy Game Menu UI"),
414                        TextFont {
415                            font_size: FontSize::Px(67.0),
416                            ..default()
417                        },
418                        TextColor(TEXT_COLOR),
419                        Node {
420                            margin: UiRect::all(px(50)),
421                            ..default()
422                        },
423                    ),
424                    // Display three buttons for each action available from the main menu:
425                    // - new game
426                    // - settings
427                    // - quit
428                    (
429                        Button,
430                        button_node.clone(),
431                        BackgroundColor(NORMAL_BUTTON),
432                        MenuButtonAction::Play,
433                        children![
434                            (ImageNode::new(right_icon), button_icon_node.clone()),
435                            (
436                                Text::new("New Game"),
437                                button_text_font.clone(),
438                                TextColor(TEXT_COLOR),
439                            ),
440                        ]
441                    ),
442                    (
443                        Button,
444                        button_node.clone(),
445                        BackgroundColor(NORMAL_BUTTON),
446                        MenuButtonAction::Settings,
447                        children![
448                            (ImageNode::new(wrench_icon), button_icon_node.clone()),
449                            (
450                                Text::new("Settings"),
451                                button_text_font.clone(),
452                                TextColor(TEXT_COLOR),
453                            ),
454                        ]
455                    ),
456                    (
457                        Button,
458                        button_node,
459                        BackgroundColor(NORMAL_BUTTON),
460                        MenuButtonAction::Quit,
461                        children![
462                            (ImageNode::new(exit_icon), button_icon_node),
463                            (Text::new("Quit"), button_text_font, TextColor(TEXT_COLOR),),
464                        ]
465                    ),
466                ]
467            )],
468        ));
469    }
examples/ui/images/image_node.rs (line 30)
13fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
14    // Ui camera
15    commands.spawn(Camera2d);
16
17    commands.spawn((
18        // This root Node serves as a container for the ImageNode.
19        // In this case, it will center the item on the screen.
20        Node {
21            width: percent(100),
22            height: percent(100),
23            align_items: AlignItems::Center,
24            justify_content: JustifyContent::Center,
25            ..default()
26        },
27        // Child Nodes are added with the `children!` macro.
28        children![(
29            // Create a new `ImageNode` with the given texture.
30            ImageNode::new(asset_server.load("branding/icon.png")),
31            // Child Node control `ImageNode` size
32            Node {
33                border: px(5.).all(),
34                padding: px(10.).all(),
35                width: px(256.),
36                height: px(256.),
37                ..default()
38            },
39            BorderColor::all(Color::WHITE),
40        )],
41    ));
42}
examples/stress_tests/many_buttons.rs (line 294)
263fn spawn_button(
264    commands: &mut ChildSpawnerCommands,
265    background_color: Color,
266    buttons: f32,
267    column: usize,
268    row: usize,
269    spawn_text: bool,
270    border: UiRect,
271    border_color: BorderColor,
272    image: Option<Handle<Image>>,
273) {
274    let width = vw(90.0 / buttons);
275    let height = vh(90.0 / buttons);
276    let margin = UiRect::axes(width * 0.05, height * 0.05);
277    let mut builder = commands.spawn((
278        Button,
279        Node {
280            width,
281            height,
282            margin,
283            align_items: AlignItems::Center,
284            justify_content: JustifyContent::Center,
285            border,
286            ..default()
287        },
288        BackgroundColor(background_color),
289        border_color,
290        IdleColor(background_color),
291    ));
292
293    if let Some(image) = image {
294        builder.insert(ImageNode::new(image));
295    }
296
297    if spawn_text {
298        builder.with_children(|parent| {
299            // These labels are split to stress test multi-span text
300            parent
301                .spawn((
302                    Text(format!("{column}, ")),
303                    TextFont {
304                        font_size: FONT_SIZE,
305                        ..default()
306                    },
307                    TextColor(Color::srgb(0.5, 0.2, 0.2)),
308                ))
309                .with_child((
310                    TextSpan(format!("{row}")),
311                    TextFont {
312                        font_size: FONT_SIZE,
313                        ..default()
314                    },
315                    TextColor(Color::srgb(0.2, 0.2, 0.5)),
316                ));
317        });
318    }
319}
examples/ui/ui_scaling.rs (line 69)
25fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
26    commands.spawn(Camera2d);
27
28    let text_font = TextFont {
29        font_size: FontSize::Px(13.),
30        ..default()
31    };
32
33    commands
34        .spawn((
35            Node {
36                width: percent(50),
37                height: percent(50),
38                position_type: PositionType::Absolute,
39                left: percent(25),
40                top: percent(25),
41                justify_content: JustifyContent::SpaceAround,
42                align_items: AlignItems::Center,
43                ..default()
44            },
45            BackgroundColor(ANTIQUE_WHITE.into()),
46        ))
47        .with_children(|parent| {
48            parent
49                .spawn((
50                    Node {
51                        width: px(40),
52                        height: px(40),
53                        ..default()
54                    },
55                    BackgroundColor(RED.into()),
56                ))
57                .with_children(|parent| {
58                    parent.spawn((Text::new("Size!"), text_font, TextColor::BLACK));
59                });
60            parent.spawn((
61                Node {
62                    width: percent(15),
63                    height: percent(15),
64                    ..default()
65                },
66                BackgroundColor(BLUE.into()),
67            ));
68            parent.spawn((
69                ImageNode::new(asset_server.load("branding/icon.png")),
70                Node {
71                    width: px(30),
72                    height: px(30),
73                    ..default()
74                },
75            ));
76        });
77}
Source

pub fn solid_color(color: Color) -> ImageNode

Create a solid color ImageNode.

This is primarily useful for debugging / mocking the extents of your image.

Source

pub fn from_atlas_image(image: Handle<Image>, atlas: TextureAtlas) -> ImageNode

Create a ImageNode from an image, with an associated texture atlas

Examples found in repository?
examples/usage/cooldown.rs (line 108)
84fn build_ability(
85    food: FoodItem,
86    texture: Handle<Image>,
87    layout: Handle<TextureAtlasLayout>,
88) -> impl Bundle {
89    let FoodItem {
90        name,
91        cooldown,
92        index,
93    } = food;
94    let name = Name::new(name);
95
96    // Every food item is a button with a child node.
97    // The child node's height will be animated to be at 100% at the beginning
98    // of a cooldown, effectively graying out the whole button, and then getting smaller over time.
99    (
100        Node {
101            width: px(80),
102            height: px(80),
103            flex_direction: FlexDirection::ColumnReverse,
104            ..default()
105        },
106        BackgroundColor(tailwind::SLATE_400.into()),
107        Button,
108        ImageNode::from_atlas_image(texture, TextureAtlas { layout, index }),
109        Cooldown(Timer::from_seconds(cooldown, TimerMode::Once)),
110        name,
111        children![(
112            Node {
113                width: percent(100),
114                height: percent(0),
115                ..default()
116            },
117            BackgroundColor(tailwind::SLATE_50.with_alpha(0.5).into()),
118        )],
119    )
120}
More examples
Hide additional examples
examples/ui/images/ui_texture_atlas.rs (lines 46-49)
18fn setup(
19    mut commands: Commands,
20    asset_server: Res<AssetServer>,
21    mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
22) {
23    // Camera
24    commands.spawn(Camera2d);
25
26    let font_size: f32 = 20.;
27    let text_font = TextFont::from_font_size(20.);
28
29    let texture_handle = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png");
30    let texture_atlas = TextureAtlasLayout::from_grid(UVec2::splat(24), 7, 1, None, None);
31    let texture_atlas_handle = texture_atlases.add(texture_atlas);
32
33    // root node
34    commands
35        .spawn(Node {
36            width: percent(100),
37            height: percent(100),
38            flex_direction: FlexDirection::Column,
39            justify_content: JustifyContent::Center,
40            align_items: AlignItems::Center,
41            row_gap: px(font_size * 2.),
42            ..default()
43        })
44        .with_children(|parent| {
45            parent.spawn((
46                ImageNode::from_atlas_image(
47                    texture_handle,
48                    TextureAtlas::from(texture_atlas_handle),
49                ),
50                Node {
51                    width: px(256),
52                    height: px(256),
53                    ..default()
54                },
55                BackgroundColor(ANTIQUE_WHITE.into()),
56                Outline::new(px(8), Val::ZERO, CRIMSON.into()),
57            ));
58            parent
59                .spawn((Text::new("press "), text_font.clone()))
60                .with_child((
61                    TextSpan::new("space"),
62                    TextColor(YELLOW.into()),
63                    text_font.clone(),
64                ))
65                .with_child((TextSpan::new(" to advance frames"), text_font));
66        });
67}
examples/ui/images/ui_texture_atlas_slice.rs (lines 82-88)
47fn setup(
48    mut commands: Commands,
49    asset_server: Res<AssetServer>,
50    mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
51) {
52    let texture_handle = asset_server.load("textures/fantasy_ui_borders/border_sheet.png");
53    let atlas_layout =
54        TextureAtlasLayout::from_grid(UVec2::new(50, 50), 6, 6, Some(UVec2::splat(2)), None);
55    let atlas_layout_handle = texture_atlases.add(atlas_layout);
56
57    let slicer = TextureSlicer {
58        border: BorderRect::all(24.0),
59        center_scale_mode: SliceScaleMode::Stretch,
60        sides_scale_mode: SliceScaleMode::Stretch,
61        max_corner_scale: 1.0,
62    };
63    // ui camera
64    commands.spawn(Camera2d);
65    commands
66        .spawn(Node {
67            width: percent(100),
68            height: percent(100),
69            align_items: AlignItems::Center,
70            justify_content: JustifyContent::Center,
71            ..default()
72        })
73        .with_children(|parent| {
74            for (idx, [w, h]) in [
75                (0, [150.0, 150.0]),
76                (7, [300.0, 150.0]),
77                (13, [150.0, 300.0]),
78            ] {
79                parent
80                    .spawn((
81                        Button,
82                        ImageNode::from_atlas_image(
83                            texture_handle.clone(),
84                            TextureAtlas {
85                                index: idx,
86                                layout: atlas_layout_handle.clone(),
87                            },
88                        )
89                        .with_mode(NodeImageMode::Sliced(slicer.clone())),
90                        Node {
91                            width: px(w),
92                            height: px(h),
93                            // horizontally center child text
94                            justify_content: JustifyContent::Center,
95                            // vertically center child text
96                            align_items: AlignItems::Center,
97                            margin: px(20).all(),
98                            ..default()
99                        },
100                    ))
101                    .with_children(|parent| {
102                        parent.spawn((
103                            Text::new("Button"),
104                            TextFont {
105                                font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
106                                font_size: FontSize::Px(33.0),
107                                ..default()
108                            },
109                            TextColor(Color::srgb(0.9, 0.9, 0.9)),
110                        ));
111                    });
112            }
113        });
114}
Source

pub const fn with_color(self, color: Color) -> ImageNode

Set the color tint

Source

pub const fn with_flip_x(self) -> ImageNode

Flip the image along its x-axis

Source

pub const fn with_flip_y(self) -> ImageNode

Flip the image along its y-axis

Source

pub const fn with_rect(self, rect: Rect) -> ImageNode

Source

pub const fn with_mode(self, mode: NodeImageMode) -> ImageNode

Examples found in repository?
examples/ui/images/ui_texture_atlas_slice.rs (line 89)
47fn setup(
48    mut commands: Commands,
49    asset_server: Res<AssetServer>,
50    mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
51) {
52    let texture_handle = asset_server.load("textures/fantasy_ui_borders/border_sheet.png");
53    let atlas_layout =
54        TextureAtlasLayout::from_grid(UVec2::new(50, 50), 6, 6, Some(UVec2::splat(2)), None);
55    let atlas_layout_handle = texture_atlases.add(atlas_layout);
56
57    let slicer = TextureSlicer {
58        border: BorderRect::all(24.0),
59        center_scale_mode: SliceScaleMode::Stretch,
60        sides_scale_mode: SliceScaleMode::Stretch,
61        max_corner_scale: 1.0,
62    };
63    // ui camera
64    commands.spawn(Camera2d);
65    commands
66        .spawn(Node {
67            width: percent(100),
68            height: percent(100),
69            align_items: AlignItems::Center,
70            justify_content: JustifyContent::Center,
71            ..default()
72        })
73        .with_children(|parent| {
74            for (idx, [w, h]) in [
75                (0, [150.0, 150.0]),
76                (7, [300.0, 150.0]),
77                (13, [150.0, 300.0]),
78            ] {
79                parent
80                    .spawn((
81                        Button,
82                        ImageNode::from_atlas_image(
83                            texture_handle.clone(),
84                            TextureAtlas {
85                                index: idx,
86                                layout: atlas_layout_handle.clone(),
87                            },
88                        )
89                        .with_mode(NodeImageMode::Sliced(slicer.clone())),
90                        Node {
91                            width: px(w),
92                            height: px(h),
93                            // horizontally center child text
94                            justify_content: JustifyContent::Center,
95                            // vertically center child text
96                            align_items: AlignItems::Center,
97                            margin: px(20).all(),
98                            ..default()
99                        },
100                    ))
101                    .with_children(|parent| {
102                        parent.spawn((
103                            Text::new("Button"),
104                            TextFont {
105                                font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
106                                font_size: FontSize::Px(33.0),
107                                ..default()
108                            },
109                            TextColor(Color::srgb(0.9, 0.9, 0.9)),
110                        ));
111                    });
112            }
113        });
114}
More examples
Hide additional examples
examples/testbed/full_ui.rs (line 350)
31fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
32    // Camera
33    commands.spawn((Camera2d, IsDefaultUiCamera, BoxShadowSamples(6)));
34
35    // root node
36    commands
37        .spawn(Node {
38            width: percent(100),
39            height: percent(100),
40            justify_content: JustifyContent::SpaceBetween,
41            ..default()
42        })
43        .insert(Pickable::IGNORE)
44        .with_children(|parent| {
45            // left vertical fill (border)
46            parent
47                .spawn((
48                    Node {
49                        width: px(200),
50                        border: UiRect::all(px(2)),
51                        ..default()
52                    },
53                    BackgroundColor(Color::srgb(0.65, 0.65, 0.65)),
54                ))
55                .with_children(|parent| {
56                    // left vertical fill (content)
57                    parent
58                        .spawn((
59                            Node {
60                                width: percent(100),
61                                flex_direction: FlexDirection::Column,
62                                padding: UiRect::all(px(5)),
63                                row_gap: px(5),
64                                ..default()
65                            },
66                            BackgroundColor(Color::srgb(0.15, 0.15, 0.15)),
67                            Visibility::Visible,
68                        ))
69                        .with_children(|parent| {
70                            // text
71                            parent.spawn((
72                                Text::new("Text Example"),
73                                TextFont {
74                                    font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
75                                    font_size: FontSize::Px(25.0),
76                                    ..default()
77                                },
78                                // Because this is a distinct label widget and
79                                // not button/list item text, this is necessary
80                                // for accessibility to treat the text accordingly.
81                                Label,
82                            ));
83
84                            #[cfg(feature = "bevy_ui_debug")]
85                            {
86                                // Debug overlay text
87                                parent.spawn((
88                                    Text::new("Press Space to toggle debug outlines."),
89                                    TextFont {
90                                        font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
91                                        ..default()
92                                    },
93                                    Label,
94                                ));
95
96                                parent.spawn((
97                                    Text::new("V: toggle UI root's visibility"),
98                                    TextFont {
99                                        font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
100                                        font_size: FontSize::Px(12.),
101                                        ..default()
102                                    },
103                                    Label,
104                                ));
105
106                                parent.spawn((
107                                    Text::new("S: toggle outlines for hidden nodes"),
108                                    TextFont {
109                                        font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
110                                        font_size: FontSize::Px(12.),
111                                        ..default()
112                                    },
113                                    Label,
114                                ));
115                                parent.spawn((
116                                    Text::new("C: toggle outlines for clipped nodes"),
117                                    TextFont {
118                                        font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
119                                        font_size: FontSize::Px(12.),
120                                        ..default()
121                                    },
122                                    Label,
123                                ));
124                            }
125                            #[cfg(not(feature = "bevy_ui_debug"))]
126                            parent.spawn((
127                                Text::new("Try enabling feature \"bevy_ui_debug\"."),
128                                TextFont {
129                                    font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
130                                    ..default()
131                                },
132                                Label,
133                            ));
134                        });
135                });
136            // right vertical fill
137            parent
138                .spawn(Node {
139                    flex_direction: FlexDirection::Column,
140                    justify_content: JustifyContent::Center,
141                    align_items: AlignItems::Center,
142                    width: px(200),
143                    ..default()
144                })
145                .with_children(|parent| {
146                    // Title
147                    parent.spawn((
148                        Text::new("Scrolling list"),
149                        TextFont {
150                            font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
151                            font_size: FontSize::Px(21.),
152                            ..default()
153                        },
154                        Label,
155                    ));
156                    // Scrolling list
157                    parent
158                        .spawn((
159                            Node {
160                                flex_direction: FlexDirection::Column,
161                                align_self: AlignSelf::Stretch,
162                                height: percent(50),
163                                overflow: Overflow::scroll_y(),
164                                ..default()
165                            },
166                            BackgroundColor(Color::srgb(0.10, 0.10, 0.10)),
167                        ))
168                        .with_children(|parent| {
169                            parent
170                                .spawn((
171                                    Node {
172                                        flex_direction: FlexDirection::Column,
173                                        ..Default::default()
174                                    },
175                                    BackgroundGradient::from(LinearGradient::to_bottom(vec![
176                                        ColorStop::auto(NAVY),
177                                        ColorStop::auto(Color::BLACK),
178                                    ])),
179                                    Pickable {
180                                        should_block_lower: false,
181                                        ..Default::default()
182                                    },
183                                ))
184                                .with_children(|parent| {
185                                    // List items
186                                    for i in 0..25 {
187                                        parent
188                                            .spawn((
189                                                Text(format!("Item {i}")),
190                                                TextFont {
191                                                    font: asset_server
192                                                        .load("fonts/FiraSans-Bold.ttf")
193                                                        .into(),
194                                                    ..default()
195                                                },
196                                                Label,
197                                                AccessibilityNode(Accessible::new(Role::ListItem)),
198                                            ))
199                                            .insert(Pickable {
200                                                should_block_lower: false,
201                                                ..default()
202                                            });
203                                    }
204                                });
205                        });
206                });
207
208            parent
209                .spawn(Node {
210                    left: px(210),
211                    bottom: px(10),
212                    position_type: PositionType::Absolute,
213                    ..default()
214                })
215                .with_children(|parent| {
216                    parent
217                        .spawn((
218                            Node {
219                                width: px(200),
220                                height: px(200),
221                                border: UiRect::all(px(20)),
222                                flex_direction: FlexDirection::Column,
223                                justify_content: JustifyContent::Center,
224                                ..default()
225                            },
226                            BorderColor::all(LIME),
227                            BackgroundColor(Color::srgb(0.8, 0.8, 1.)),
228                        ))
229                        .with_children(|parent| {
230                            parent.spawn((
231                                ImageNode::new(asset_server.load("branding/bevy_logo_light.png")),
232                                // Uses the transform to rotate the logo image by 45 degrees
233                                Node {
234                                    border_radius: BorderRadius::all(px(10)),
235                                    ..Default::default()
236                                },
237                                UiTransform {
238                                    rotation: Rot2::radians(0.25 * PI),
239                                    ..Default::default()
240                                },
241                                Outline {
242                                    width: px(2),
243                                    offset: px(4),
244                                    color: DARK_GRAY.into(),
245                                },
246                            ));
247                        });
248                });
249
250            let shadow_style = ShadowStyle {
251                color: Color::BLACK.with_alpha(0.5),
252                blur_radius: px(2),
253                x_offset: px(10),
254                y_offset: px(10),
255                ..default()
256            };
257
258            // render order test: reddest in the back, whitest in the front (flex center)
259            parent
260                .spawn(Node {
261                    width: percent(100),
262                    height: percent(100),
263                    position_type: PositionType::Absolute,
264                    align_items: AlignItems::Center,
265                    justify_content: JustifyContent::Center,
266                    ..default()
267                })
268                .insert(Pickable::IGNORE)
269                .with_children(|parent| {
270                    parent
271                        .spawn((
272                            Node {
273                                width: px(100),
274                                height: px(100),
275                                ..default()
276                            },
277                            BackgroundColor(Color::srgb(1.0, 0.0, 0.)),
278                            BoxShadow::from(shadow_style),
279                        ))
280                        .with_children(|parent| {
281                            parent.spawn((
282                                Node {
283                                    // Take the size of the parent node.
284                                    width: percent(100),
285                                    height: percent(100),
286                                    position_type: PositionType::Absolute,
287                                    left: px(20),
288                                    bottom: px(20),
289                                    ..default()
290                                },
291                                BackgroundColor(Color::srgb(1.0, 0.3, 0.3)),
292                                BoxShadow::from(shadow_style),
293                            ));
294                            parent.spawn((
295                                Node {
296                                    width: percent(100),
297                                    height: percent(100),
298                                    position_type: PositionType::Absolute,
299                                    left: px(40),
300                                    bottom: px(40),
301                                    ..default()
302                                },
303                                BackgroundColor(Color::srgb(1.0, 0.5, 0.5)),
304                                BoxShadow::from(shadow_style),
305                            ));
306                            parent.spawn((
307                                Node {
308                                    width: percent(100),
309                                    height: percent(100),
310                                    position_type: PositionType::Absolute,
311                                    left: px(60),
312                                    bottom: px(60),
313                                    ..default()
314                                },
315                                BackgroundColor(Color::srgb(0.0, 0.7, 0.7)),
316                                BoxShadow::from(shadow_style),
317                            ));
318                            // alpha test
319                            parent.spawn((
320                                Node {
321                                    width: percent(100),
322                                    height: percent(100),
323                                    position_type: PositionType::Absolute,
324                                    left: px(80),
325                                    bottom: px(80),
326                                    ..default()
327                                },
328                                BackgroundColor(Color::srgba(1.0, 0.9, 0.9, 0.4)),
329                                BoxShadow::from(ShadowStyle {
330                                    color: Color::BLACK.with_alpha(0.3),
331                                    ..shadow_style
332                                }),
333                            ));
334                        });
335                });
336            // bevy logo (flex center)
337            parent
338                .spawn(Node {
339                    width: percent(100),
340                    position_type: PositionType::Absolute,
341                    justify_content: JustifyContent::Center,
342                    align_items: AlignItems::FlexStart,
343                    ..default()
344                })
345                .with_children(|parent| {
346                    // bevy logo (image)
347                    parent
348                        .spawn((
349                            ImageNode::new(asset_server.load("branding/bevy_logo_dark_big.png"))
350                                .with_mode(NodeImageMode::Stretch),
351                            Node {
352                                width: px(500),
353                                height: px(125),
354                                margin: UiRect::top(vmin(5)),
355                                ..default()
356                            },
357                        ))
358                        .with_children(|parent| {
359                            // alt text
360                            // This UI node takes up no space in the layout and the `Text` component is used by the accessibility module
361                            // and is not rendered.
362                            parent.spawn((
363                                Node {
364                                    display: Display::None,
365                                    ..default()
366                                },
367                                Text::new("Bevy logo"),
368                            ));
369                        });
370                });
371
372            // four bevy icons demonstrating image flipping
373            parent
374                .spawn(Node {
375                    width: percent(100),
376                    height: percent(100),
377                    position_type: PositionType::Absolute,
378                    justify_content: JustifyContent::Center,
379                    align_items: AlignItems::FlexEnd,
380                    column_gap: px(10),
381                    padding: UiRect::all(px(10)),
382                    ..default()
383                })
384                .insert(Pickable::IGNORE)
385                .with_children(|parent| {
386                    for (flip_x, flip_y) in
387                        [(false, false), (false, true), (true, true), (true, false)]
388                    {
389                        parent.spawn((
390                            ImageNode {
391                                image: asset_server.load("branding/icon.png"),
392                                flip_x,
393                                flip_y,
394                                ..default()
395                            },
396                            Node {
397                                // The height will be chosen automatically to preserve the image's aspect ratio
398                                width: px(75),
399                                ..default()
400                            },
401                        ));
402                    }
403                });
404        });
405}

Trait Implementations§

Source§

impl AsAssetId for ImageNode

Source§

type Asset = Image

The underlying asset type.
Source§

fn as_asset_id(&self) -> AssetId<<ImageNode as AsAssetId>::Asset>

Retrieves the asset id from this component.
Source§

impl Clone for ImageNode

Source§

fn clone(&self) -> ImageNode

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Component for ImageNode
where ImageNode: Send + Sync + 'static,

Required Components: Node, ImageNodeSize.

A component’s Required Components are inserted whenever it is inserted. Note that this will also insert the required components of the required components, recursively, in depth-first order.

Source§

const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::Table

A constant indicating the storage type used for this component.
Source§

type Mutability = Mutable

A marker type to assist Bevy with determining if this component is mutable, or immutable. Mutable components will have Component<Mutability = Mutable>, while immutable components will instead have Component<Mutability = Immutable>. Read more
Source§

fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )

Registers required components. Read more
Source§

fn clone_behavior() -> ComponentCloneBehavior

Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component. Read more
Source§

fn relationship_accessor() -> Option<ComponentRelationshipAccessor<ImageNode>>

Returns ComponentRelationshipAccessor required for working with relationships in dynamic contexts. Read more
Source§

fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_add ComponentHook for this Component if one is defined.
Source§

fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_insert ComponentHook for this Component if one is defined.
Source§

fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_discard ComponentHook for this Component if one is defined.
Source§

fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_remove ComponentHook for this Component if one is defined.
Source§

fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_despawn ComponentHook for this Component if one is defined.
Source§

fn map_entities<E>(_this: &mut Self, _mapper: &mut E)
where E: EntityMapper,

Maps the entities on this component using the given EntityMapper. This is used to remap entities in contexts like scenes and entity cloning. When deriving Component, this is populated by annotating fields containing entities with #[entities] Read more
Source§

impl Debug for ImageNode

Source§

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

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

impl Default for ImageNode

Source§

fn default() -> ImageNode

A transparent 1x1 image with a solid white tint.

§Warning

This will be invisible by default. To set this to a visible image, you need to set the texture field to a valid image handle, or use Handle<Image>’s default 1x1 solid white texture (as is done in ImageNode::solid_color).

Source§

impl From<Handle<Image>> for ImageNode

Source§

fn from(texture: Handle<Image>) -> ImageNode

Converts to this type from the input type.
Source§

impl FromArg for ImageNode

Source§

type This<'from_arg> = ImageNode

The type to convert into. Read more
Source§

fn from_arg(arg: Arg<'_>) -> Result<<ImageNode as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl FromReflect for ImageNode

Source§

fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<ImageNode>

Constructs a concrete instance of Self from a reflected value.
Source§

fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>

Attempts to downcast the given value to Self using, constructing the value using from_reflect if that fails. Read more
Source§

impl FromTemplate for ImageNode

Source§

impl GetOwnership for ImageNode

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetTypeRegistration for ImageNode

Source§

fn get_type_registration() -> TypeRegistration

Returns the default TypeRegistration for this type.
Source§

fn register_type_dependencies(registry: &mut TypeRegistry)

Registers other types needed by this type. Read more
Source§

impl IntoReturn for ImageNode

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where ImageNode: 'into_return,

Converts Self into a Return value.
Source§

impl PartialReflect for ImageNode

Source§

fn get_represented_type_info(&self) -> Option<&'static TypeInfo>

Returns the TypeInfo of the type represented by this value. Read more
Source§

fn try_apply( &mut self, value: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>

Tries to apply a reflected value to this value. Read more
Source§

fn reflect_kind(&self) -> ReflectKind

Returns a zero-sized enumeration of “kinds” of type. Read more
Source§

fn reflect_ref(&self) -> ReflectRef<'_>

Returns an immutable enumeration of “kinds” of type. Read more
Source§

fn reflect_mut(&mut self) -> ReflectMut<'_>

Returns a mutable enumeration of “kinds” of type. Read more
Source§

fn reflect_owned(self: Box<ImageNode>) -> ReflectOwned

Returns an owned enumeration of “kinds” of type. Read more
Source§

fn try_into_reflect( self: Box<ImageNode>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>

Attempts to cast this type to a boxed, fully-reflected value.
Source§

fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>

Attempts to cast this type to a fully-reflected value.
Source§

fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>

Attempts to cast this type to a mutable, fully-reflected value.
Source§

fn into_partial_reflect(self: Box<ImageNode>) -> Box<dyn PartialReflect>

Casts this type to a boxed, reflected value. Read more
Source§

fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)

Casts this type to a reflected value. Read more
Source§

fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)

Casts this type to a mutable, reflected value. Read more
Source§

fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>

Returns a “partial equality” comparison result. Read more
Source§

fn reflect_partial_cmp( &self, value: &(dyn PartialReflect + 'static), ) -> Option<Ordering>

Returns a “partial comparison” result. Read more
Source§

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

Debug formatter for the value. Read more
Source§

fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>

Attempts to clone Self using reflection. Read more
Source§

fn apply(&mut self, value: &(dyn PartialReflect + 'static))

Applies a reflected value to this value. Read more
Source§

fn to_dynamic(&self) -> Box<dyn PartialReflect>

Converts this reflected value into its dynamic representation based on its kind. Read more
Source§

fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
where T: 'static, Self: Sized + TypePath,

For a type implementing PartialReflect, combines reflect_clone and take in a useful fashion, automatically constructing an appropriate ReflectCloneError if the downcast fails.
Source§

fn reflect_hash(&self) -> Option<u64>

Returns a hash of the value (which includes the type). Read more
Source§

fn is_dynamic(&self) -> bool

Indicates whether or not this type is a dynamic type. Read more
Source§

impl Reflect for ImageNode

Source§

fn into_any(self: Box<ImageNode>) -> Box<dyn Any>

Returns the value as a Box<dyn Any>. Read more
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Returns the value as a &dyn Any. Read more
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Returns the value as a &mut dyn Any. Read more
Source§

fn into_reflect(self: Box<ImageNode>) -> Box<dyn Reflect>

Casts this type to a boxed, fully-reflected value.
Source§

fn as_reflect(&self) -> &(dyn Reflect + 'static)

Casts this type to a fully-reflected value.
Source§

fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)

Casts this type to a mutable, fully-reflected value.
Source§

fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>

Performs a type-checked assignment of a reflected value to this value. Read more
Source§

impl Struct for ImageNode

Source§

fn field(&self, name: &str) -> Option<&(dyn PartialReflect + 'static)>

Gets a reference to the value of the field named name as a &dyn PartialReflect.
Source§

fn field_mut( &mut self, name: &str, ) -> Option<&mut (dyn PartialReflect + 'static)>

Gets a mutable reference to the value of the field named name as a &mut dyn PartialReflect.
Source§

fn field_at(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>

Gets a reference to the value of the field with index index as a &dyn PartialReflect.
Source§

fn field_at_mut( &mut self, index: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>

Gets a mutable reference to the value of the field with index index as a &mut dyn PartialReflect.
Source§

fn name_at(&self, index: usize) -> Option<&str>

Gets the name of the field with index index.
Source§

fn index_of_name(&self, name: &str) -> Option<usize>

Gets the index of the field with the given name.
Source§

fn field_len(&self) -> usize

Returns the number of fields in the struct.
Source§

fn iter_fields(&self) -> FieldIter<'_>

Returns an iterator over the values of the reflectable fields for this struct.
Source§

fn to_dynamic_struct(&self) -> DynamicStruct

Creates a new DynamicStruct from this struct.
Source§

fn get_represented_struct_info(&self) -> Option<&'static StructInfo>

Will return None if TypeInfo is not available.
Source§

impl TypePath for ImageNode

Source§

fn type_path() -> &'static str

Returns the fully qualified path of the underlying type. Read more
Source§

fn short_type_path() -> &'static str

Returns a short, pretty-print enabled path to the type. Read more
Source§

fn type_ident() -> Option<&'static str>

Returns the name of the type, or None if it is anonymous. Read more
Source§

fn crate_name() -> Option<&'static str>

Returns the name of the crate the type is in, or None if it is anonymous. Read more
Source§

fn module_path() -> Option<&'static str>

Returns the path to the module the type is in, or None if it is anonymous. Read more
Source§

impl Typed for ImageNode

Source§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.
Source§

impl Unpin for ImageNode
where [()]: for<'a> SpecializeFromTemplate,

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<C> Bundle for C
where C: Component,

Source§

fn component_ids( components: &mut ComponentsRegistrator<'_>, ) -> impl Iterator<Item = ComponentId> + use<C>

Source§

fn get_component_ids( components: &Components, ) -> impl Iterator<Item = Option<ComponentId>>

Return a iterator over this Bundle’s component ids. This will be None if the component has not been registered.
Source§

impl<C> BundleFromComponents for C
where C: Component,

Source§

unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
where F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>, C: Sized,

Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

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

Source§

impl<C> DynamicBundle for C
where C: Component,

Source§

type Effect = ()

An operation on the entity that happens after inserting this bundle.
Source§

unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect

Moves the components out of the bundle. Read more
Source§

unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )

Applies the after-effects of spawning this bundle. Read more
Source§

impl<T> DynamicTypePath for T
where T: TypePath,

Source§

impl<T> DynamicTyped for T
where T: Typed,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> FromWorld for T
where T: Default,

Source§

fn from_world(_world: &mut World) -> T

Creates Self using default().

Source§

impl<S> GetField for S
where S: Struct,

Source§

fn get_field<T>(&self, name: &str) -> Option<&T>
where T: Reflect,

Gets a reference to the value of the field named name, downcast to T.
Source§

fn get_field_mut<T>(&mut self, name: &str) -> Option<&mut T>
where T: Reflect,

Gets a mutable reference to the value of the field named name, downcast to T.
Source§

impl<T> GetPath for T
where T: Reflect + ?Sized,

Source§

fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a reference to the value specified by path. Read more
Source§

fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a mutable reference to the value specified by path. Read more
Source§

fn path<'p, T>( &self, path: impl ReflectPath<'p>, ) -> Result<&T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed reference to the value specified by path. Read more
Source§

fn path_mut<'p, T>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed mutable reference to the value specified by path. Read more
Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> HitDataExtra for T
where T: Send + Sync + Debug + Any + 'static,

Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> InitializeFromFunction<T> for T

Source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where 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.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

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

Source§

fn into_sample(self) -> T

Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T> NoneValue for T
where T: Default,

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
Source§

impl<G> PatchFromTemplate for G
where G: FromTemplate,

Source§

type Template = <G as FromTemplate>::Template

The Template that will be patched.
Source§

fn patch<F>(func: F) -> TemplatePatch<F, <G as PatchFromTemplate>::Template>
where F: FnOnce(&mut <G as PatchFromTemplate>::Template, &mut ResolveContext<'_>),

Takes a “patch function” func, and turns it into a TemplatePatch.
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Reflectable for T

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Settings for T
where T: 'static + Send + Sync,

Source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

Source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
Source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

Source§

fn super_from(input: T) -> O

Convert from a type to another type.
Source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

Source§

fn super_into(self) -> O

Convert from a type to another type.
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

fn to_sample_(self) -> U

Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

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

Source§

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 T
where U: TryFrom<T>,

Source§

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.
Source§

impl<T> TypeData for T
where T: 'static + Send + Sync + Clone,

Source§

fn clone_type_data(&self) -> Box<dyn TypeData>

Creates a type-erased clone of this value.
Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more