docs/bevy/examples/window/window_resizing.rs 2.4 K · 83 lines · raw · history

1 //! This example illustrates how to resize windows, and how to respond to a window being resized.
2 use bevy::{prelude::*, window::WindowResized};
3
4 fn main() {
5 App::new()
6 .insert_resource(ResolutionSettings {
7 large: Vec2::new(1920.0, 1080.0),
8 medium: Vec2::new(800.0, 600.0),
9 small: Vec2::new(640.0, 360.0),
10 })
11 .add_plugins(DefaultPlugins)
12 .add_systems(Startup, (setup_camera, setup_ui))
13 .add_systems(Update, (on_resize_system, toggle_resolution))
14 .run();
15 }
16
17 /// Marker component for the text that displays the current resolution.
18 #[derive(Component)]
19 struct ResolutionText;
20
21 /// Stores the various window-resolutions we can select between.
22 #[derive(Resource)]
23 struct ResolutionSettings {
24 large: Vec2,
25 medium: Vec2,
26 small: Vec2,
27 }
28
29 // Spawns the camera that draws UI
30 fn setup_camera(mut commands: Commands) {
31 commands.spawn(Camera2d);
32 }
33
34 // Spawns the UI
35 fn setup_ui(mut commands: Commands) {
36 // Node that fills entire background
37 commands
38 .spawn(Node {
39 width: percent(100),
40 ..default()
41 })
42 // Text where we display current resolution
43 .with_child((
44 Text::new("Resolution"),
45 TextFont {
46 font_size: FontSize::Px(42.0),
47 ..default()
48 },
49 ResolutionText,
50 ));
51 }
52
53 /// This system shows how to request the window to a new resolution
54 fn toggle_resolution(
55 keys: Res<ButtonInput<KeyCode>>,
56 mut window: Single<&mut Window>,
57 resolution: Res<ResolutionSettings>,
58 ) {
59 if keys.just_pressed(KeyCode::Digit1) {
60 let res = resolution.small;
61 window.resolution.set(res.x, res.y);
62 }
63 if keys.just_pressed(KeyCode::Digit2) {
64 let res = resolution.medium;
65 window.resolution.set(res.x, res.y);
66 }
67 if keys.just_pressed(KeyCode::Digit3) {
68 let res = resolution.large;
69 window.resolution.set(res.x, res.y);
70 }
71 }
72
73 /// This system shows how to respond to a window being resized.
74 /// Whenever the window is resized, the text will update with the new resolution.
75 fn on_resize_system(
76 mut text: Single<&mut Text, With<ResolutionText>>,
77 mut resize_reader: MessageReader<WindowResized>,
78 ) {
79 for e in resize_reader.read() {
80 // When resolution is being changed
81 text.0 = format!("{:.1} x {:.1}", e.width, e.height);
82 }
83 }