use bevy::prelude::*;
const VIRTUAL_WIDTH: f32 = 1920.0;
const VIRTUAL_HEIGHT: f32 = 1080.0;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, update_ui_scale)
.run();
}
fn setup(mut commands: Commands) {
// 相机
commands.spawn((Camera2d, Camera::default()));
// UI 根容器
commands
.spawn((
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::BLACK),
))
.with_children(|parent| {
// 固定尺寸的内容区域
parent
.spawn((
Node {
width: Val::Px(VIRTUAL_WIDTH),
height: Val::Px(VIRTUAL_HEIGHT),
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::srgb(0.2, 0.2, 0.2)),
))
.with_children(|parent| {
// 示例 UI 元素 - 固定位置的按钮
parent.spawn((
Node {
width: Val::Px(200.0),
height: Val::Px(80.0),
position_type: PositionType::Absolute,
left: Val::Px(100.0),
top: Val::Px(100.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::srgb(0.8, 0.2, 0.2)),
))
.with_children(|parent| {
parent.spawn((
Text::new("固定按钮"),
TextFont {
font_size: 24.0,
..default()
},
TextColor(Color::WHITE),
));
});
// 另一个固定位置的 UI 元素
parent.spawn((
Node {
width: Val::Px(150.0),
height: Val::Px(60.0),
position_type: PositionType::Absolute,
right: Val::Px(50.0),
bottom: Val::Px(50.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::srgb(0.2, 0.8, 0.2)),
))
.with_children(|parent| {
parent.spawn((
Text::new("右下角"),
TextFont {
font_size: 20.0,
..default()
},
TextColor(Color::WHITE),
));
});
// 标题文本
parent.spawn((
Text::new("固定布局 UI 系统"),
TextFont {
font_size: 48.0,
..default()
},
TextColor(Color::WHITE),
));
});
});
}
fn update_ui_scale(
windows: Query<&Window>,
mut ui_scale: ResMut<UiScale>,
) {
if let Some(window) = windows.iter().next() {
let window_width = window.width();
let window_height = window.height();
// 计算缩放比例,保持宽高比
let scale_x = window_width / VIRTUAL_WIDTH;
let scale_y = window_height / VIRTUAL_HEIGHT;
let scale = scale_x.min(scale_y);
ui_scale.0 = scale;
}
}