Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/ui/layout/anchor_layout.rs
9331 views
1
//! Shows an "anchor layout" style of ui layout
2
use bevy::prelude::*;
3
4
const MARGIN: Val = Val::Px(12.);
5
6
fn main() {
7
App::new()
8
.add_plugins(DefaultPlugins.set(WindowPlugin {
9
primary_window: Some(Window {
10
title: "Bevy Anchor Layout Example".to_string(),
11
..default()
12
}),
13
..default()
14
}))
15
.add_systems(Startup, spawn_layout)
16
.run();
17
}
18
19
fn spawn_layout(mut commands: Commands, asset_server: Res<AssetServer>) {
20
let font = asset_server.load("fonts/FiraSans-Bold.ttf");
21
commands.spawn(Camera2d);
22
23
let rows = [
24
(
25
"left: 10px\ntop: 10px",
26
Node {
27
left: px(10),
28
top: px(10),
29
..default()
30
},
31
),
32
(
33
"center: 10px\ntop: 10px",
34
Node {
35
margin: auto().horizontal(),
36
top: px(10),
37
..default()
38
},
39
),
40
(
41
"right: 10px\ntop: 10px",
42
Node {
43
right: px(10),
44
top: px(10),
45
..default()
46
},
47
),
48
(
49
"left: 10px\ncenter: 10px",
50
Node {
51
left: px(10),
52
margin: UiRect::vertical(auto()),
53
..default()
54
},
55
),
56
(
57
"center: 10px\ncenter: 10px",
58
Node {
59
margin: UiRect::all(auto()),
60
..default()
61
},
62
),
63
(
64
"right: 10px\ncenter: 10px",
65
Node {
66
right: px(10),
67
margin: UiRect::vertical(auto()),
68
..default()
69
},
70
),
71
(
72
"left: 10px\nbottom: 10px",
73
Node {
74
left: px(10),
75
bottom: px(10),
76
..default()
77
},
78
),
79
(
80
"center: 10px\nbottom: 10px",
81
Node {
82
margin: UiRect::horizontal(auto()),
83
bottom: px(10),
84
..default()
85
},
86
),
87
(
88
"right: 10px\nbottom: 10px",
89
Node {
90
right: px(10),
91
bottom: px(10),
92
..default()
93
},
94
),
95
];
96
97
// let font = font.clone();
98
commands.spawn((
99
Node {
100
// fill the entire window
101
width: percent(100),
102
height: percent(100),
103
padding: MARGIN.all(),
104
row_gap: MARGIN,
105
column_gap: MARGIN,
106
display: Display::Grid,
107
grid_template_columns: RepeatedGridTrack::fr(3, 1.),
108
grid_template_rows: RepeatedGridTrack::fr(3, 1.),
109
..default()
110
},
111
BackgroundColor(Color::BLACK),
112
Children::spawn(SpawnIter(
113
rows.into_iter()
114
.map(move |v| anchored_node(font.clone(), v.1, v.0)),
115
)),
116
));
117
}
118
119
fn anchored_node(font: Handle<Font>, node: Node, label: &str) -> impl Bundle {
120
(
121
// outer gray box
122
Node {
123
grid_column: GridPlacement::span(1),
124
grid_row: GridPlacement::span(1),
125
..default()
126
},
127
BackgroundColor(Color::srgb(0.25, 0.25, 0.25)),
128
children![
129
// inner label box
130
(
131
Node {
132
display: Display::Block,
133
padding: UiRect::axes(px(5), px(1)),
134
position_type: PositionType::Absolute,
135
..node
136
},
137
BackgroundColor(Color::srgb(1., 0.066, 0.349)),
138
children![(Text::new(label), TextFont::from(font), TextColor::BLACK,)],
139
)
140
],
141
)
142
}
143
144