From 55cc93a7bee21507343a2acdc7cf2bc34ff741dc Mon Sep 17 00:00:00 2001 From: Marco Meijer <46689298+MarcoMeijer@users.noreply.github.com> Date: Fri, 22 Nov 2024 19:21:45 +0100 Subject: [PATCH] fix: setting content size to rect size if image has a rect (#16457) # Objective When using a rect for a ui image, its content size is still equal to the size of the full image instead of the size of the rect. ## Solution Use the rect size if it is present. ## Testing I tested it using all 4 possible combinations of having a rect and texture atlas or not. See the showcase section. --- ## Showcase
Click to view showcase ```rust use bevy::prelude::*; fn main() { App::new() .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest())) .add_systems(Startup, create_ui) .run(); } fn create_ui( mut commands: Commands, assets: Res, mut texture_atlas_layouts: ResMut>, mut ui_scale: ResMut, ) { let texture = assets.load("textures/fantasy_ui_borders/numbered_slices.png"); let layout = TextureAtlasLayout::from_grid(UVec2::splat(16), 3, 3, None, None); let texture_atlas_layout = texture_atlas_layouts.add(layout); ui_scale.0 = 2.; commands.spawn(Camera2d::default()); commands .spawn(Node { display: Display::Flex, align_items: AlignItems::Center, ..default() }) .with_children(|parent| { // nothing parent.spawn(ImageNode::new(texture.clone())); // with rect parent.spawn(ImageNode::new(texture.clone()).with_rect(Rect::new(0., 0., 16., 16.))); // with rect and texture atlas parent.spawn( ImageNode::from_atlas_image( texture.clone(), TextureAtlas { layout: texture_atlas_layout.clone(), index: 1, }, ) .with_rect(Rect::new(0., 0., 8., 8.)), ); // with texture atlas parent.spawn(ImageNode::from_atlas_image( texture.clone(), TextureAtlas { layout: texture_atlas_layout.clone(), index: 2, }, )); }); } ``` Before this change: Screenshot 2024-11-21 at 11 55 45 After the change: Screenshot 2024-11-21 at 11 54 54
--- crates/bevy_ui/src/widget/image.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/bevy_ui/src/widget/image.rs b/crates/bevy_ui/src/widget/image.rs index 43df6aaeeb..55fb343737 100644 --- a/crates/bevy_ui/src/widget/image.rs +++ b/crates/bevy_ui/src/widget/image.rs @@ -279,10 +279,15 @@ pub fn update_image_content_size_system( continue; } - if let Some(size) = match &image.texture_atlas { - Some(atlas) => atlas.texture_rect(&atlases).map(|t| t.size()), - None => textures.get(&image.image).map(Image::size), - } { + if let Some(size) = + image + .rect + .map(|rect| rect.size().as_uvec2()) + .or_else(|| match &image.texture_atlas { + Some(atlas) => atlas.texture_rect(&atlases).map(|t| t.size()), + None => textures.get(&image.image).map(Image::size), + }) + { // Update only if size or scale factor has changed to avoid needless layout calculations if size != image_size.size || combined_scale_factor != *previous_combined_scale_factor