Path: blob/main/examples/window/scale_factor_override.rs
6595 views
//! This example illustrates how to override the window scale factor imposed by the1//! operating system.23use bevy::{prelude::*, window::WindowResolution};45#[derive(Component)]6struct CustomText;78fn main() {9App::new()10.add_plugins(DefaultPlugins.set(WindowPlugin {11primary_window: Some(Window {12resolution: WindowResolution::new(500, 300).with_scale_factor_override(1.0),13..default()14}),15..default()16}))17.add_systems(Startup, setup)18.add_systems(19Update,20(display_override, toggle_override, change_scale_factor),21)22.run();23}2425fn setup(mut commands: Commands) {26// camera27commands.spawn(Camera2d);28// root node29commands.spawn((30Node {31width: percent(100),32height: percent(100),33justify_content: JustifyContent::SpaceBetween,34..default()35},36children![(37Node {38width: px(300),39height: percent(100),40border: UiRect::all(px(2)),41..default()42},43BackgroundColor(Color::srgb(0.65, 0.65, 0.65)),44children![(45CustomText,46Text::new("Example text"),47TextFont {48font_size: 25.0,49..default()50},51Node {52align_self: AlignSelf::FlexEnd,53..default()54},55)]56)],57));58}5960/// Set the title of the window to the current override61fn display_override(62mut window: Single<&mut Window>,63mut custom_text: Single<&mut Text, With<CustomText>>,64) {65let text = format!(66"Scale factor: {:.1} {}",67window.scale_factor(),68if window.resolution.scale_factor_override().is_some() {69"(overridden)"70} else {71"(default)"72}73);7475window.title.clone_from(&text);76custom_text.0 = text;77}7879/// This system toggles scale factor overrides when enter is pressed80fn toggle_override(input: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>) {81if input.just_pressed(KeyCode::Enter) {82let scale_factor_override = window.resolution.scale_factor_override();83window84.resolution85.set_scale_factor_override(scale_factor_override.xor(Some(1.0)));86}87}8889/// This system changes the scale factor override when up or down is pressed90fn change_scale_factor(input: Res<ButtonInput<KeyCode>>, mut window: Single<&mut Window>) {91let scale_factor_override = window.resolution.scale_factor_override();92if input.just_pressed(KeyCode::ArrowUp) {93window94.resolution95.set_scale_factor_override(scale_factor_override.map(|n| n + 1.0));96} else if input.just_pressed(KeyCode::ArrowDown) {97window98.resolution99.set_scale_factor_override(scale_factor_override.map(|n| (n - 1.0).max(1.0)));100}101}102103104