ui_texture_atlas_slice/
ui_texture_atlas_slice.rs1use bevy::{
5 color::palettes::css::{GOLD, ORANGE},
6 prelude::*,
7 ui::widget::NodeImageMode,
8};
9
10fn main() {
11 App::new()
12 .add_plugins(DefaultPlugins)
13 .add_systems(Startup, setup)
14 .add_systems(Update, button_system)
15 .run();
16}
17
18fn button_system(
19 mut interaction_query: Query<
20 (&Interaction, &Children, &mut ImageNode),
21 (Changed<Interaction>, With<Button>),
22 >,
23 mut text_query: Query<&mut Text>,
24) {
25 for (interaction, children, mut image) in &mut interaction_query {
26 let mut text = text_query.get_mut(children[0]).unwrap();
27 match *interaction {
28 Interaction::Pressed => {
29 **text = "Press".to_string();
30 if let Some(atlas) = &mut image.texture_atlas {
31 atlas.index = (atlas.index + 1) % 30;
32 }
33 image.color = GOLD.into();
34 }
35 Interaction::Hovered => {
36 **text = "Hover".to_string();
37 image.color = ORANGE.into();
38 }
39 Interaction::None => {
40 **text = "Button".to_string();
41 image.color = Color::WHITE;
42 }
43 }
44 }
45}
46
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 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 justify_content: JustifyContent::Center,
95 align_items: AlignItems::Center,
97 margin: UiRect::all(px(20)),
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"),
106 font_size: 33.0,
107 ..default()
108 },
109 TextColor(Color::srgb(0.9, 0.9, 0.9)),
110 ));
111 });
112 }
113 });
114}