Path: blob/main/examples/ui/images/ui_texture_atlas_slice.rs
9374 views
//! This example illustrates how to create buttons with their texture atlases sliced1//! and kept in proportion instead of being stretched by the button dimensions23use bevy::{4color::palettes::css::{GOLD, ORANGE},5prelude::*,6ui::widget::NodeImageMode,7};89fn main() {10App::new()11.add_plugins(DefaultPlugins)12.add_systems(Startup, setup)13.add_systems(Update, button_system)14.run();15}1617fn button_system(18mut interaction_query: Query<19(&Interaction, &Children, &mut ImageNode),20(Changed<Interaction>, With<Button>),21>,22mut text_query: Query<&mut Text>,23) {24for (interaction, children, mut image) in &mut interaction_query {25let mut text = text_query.get_mut(children[0]).unwrap();26match *interaction {27Interaction::Pressed => {28**text = "Press".to_string();29if let Some(atlas) = &mut image.texture_atlas {30atlas.index = (atlas.index + 1) % 30;31}32image.color = GOLD.into();33}34Interaction::Hovered => {35**text = "Hover".to_string();36image.color = ORANGE.into();37}38Interaction::None => {39**text = "Button".to_string();40image.color = Color::WHITE;41}42}43}44}4546fn setup(47mut commands: Commands,48asset_server: Res<AssetServer>,49mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,50) {51let texture_handle = asset_server.load("textures/fantasy_ui_borders/border_sheet.png");52let atlas_layout =53TextureAtlasLayout::from_grid(UVec2::new(50, 50), 6, 6, Some(UVec2::splat(2)), None);54let atlas_layout_handle = texture_atlases.add(atlas_layout);5556let slicer = TextureSlicer {57border: BorderRect::all(24.0),58center_scale_mode: SliceScaleMode::Stretch,59sides_scale_mode: SliceScaleMode::Stretch,60max_corner_scale: 1.0,61};62// ui camera63commands.spawn(Camera2d);64commands65.spawn(Node {66width: percent(100),67height: percent(100),68align_items: AlignItems::Center,69justify_content: JustifyContent::Center,70..default()71})72.with_children(|parent| {73for (idx, [w, h]) in [74(0, [150.0, 150.0]),75(7, [300.0, 150.0]),76(13, [150.0, 300.0]),77] {78parent79.spawn((80Button,81ImageNode::from_atlas_image(82texture_handle.clone(),83TextureAtlas {84index: idx,85layout: atlas_layout_handle.clone(),86},87)88.with_mode(NodeImageMode::Sliced(slicer.clone())),89Node {90width: px(w),91height: px(h),92// horizontally center child text93justify_content: JustifyContent::Center,94// vertically center child text95align_items: AlignItems::Center,96margin: px(20).all(),97..default()98},99))100.with_children(|parent| {101parent.spawn((102Text::new("Button"),103TextFont {104font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),105font_size: FontSize::Px(33.0),106..default()107},108TextColor(Color::srgb(0.9, 0.9, 0.9)),109));110});111}112});113}114115116