窗口参数
Window 是一个组件,挂在窗口实体上。WindowPlugin 负责在 App 启动时创建主窗口实体。
rust
use bevy::prelude::*;
use bevy::window::{PresentMode, WindowPlugin, WindowResolution};
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
title: "窗口配置示例".into(),
resolution: WindowResolution::new(1024, 768),
present_mode: PresentMode::AutoVsync,
resizable: true,
decorations: true,
..default()
}),
..default()
}))
.add_systems(Startup, setup)
.add_systems(Update, update_title)
.run();
}
fn setup() {
info!("窗口已创建——1024×768,VSync 开启");
}
fn update_title(mut window: Single<&mut Window>, time: Res<Time>) {
let secs = time.elapsed().as_secs();
window.title = format!("运行了 {secs} 秒");
}Listing 35-1:窗口配置——标题、分辨率、VSync
常用字段
| 字段 | 类型 | 说明 |
|---|---|---|
title | String | 窗口标题栏文字 |
resolution | WindowResolution | 逻辑分辨率,new(width, height) 用像素值 |
present_mode | PresentMode | VSync 策略 |
mode | WindowMode | 窗口 / 全屏模式 |
position | WindowPosition | 窗口位置 |
resizable | bool | 是否可拖拽调整大小 |
decorations | bool | 是否显示标题栏和边框 |
transparent | bool | 窗口背景是否透明 |
focused | bool | 创建时是否获得焦点 |
visible | bool | 是否可见(可用于延迟显示) |
window_level | WindowLevel | 窗口层级(AlwaysOnTop / Normal / AlwaysOnBottom) |
canvas | Option<String> | Web 平台的 HTML canvas 选择器 |
fit_canvas_to_parent | bool | Web 平台是否自适应父元素大小 |
PresentMode
| 变体 | 行为 |
|---|---|
AutoVsync | 自动 VSync(默认) |
AutoNoVsync | 尽可能快地渲染 |
Fifo | 强制 VSync,帧排队 |
Mailbox | 三缓冲,新帧替换旧帧 |
WindowMode
| 变体 | 说明 |
|---|---|
Windowed | 普通窗口(默认) |
BorderlessFullscreen(MonitorSelection) | 无边框全屏 |
Fullscreen(MonitorSelection, VideoModeSelection) | 独占全屏 |
MonitorSelection 可以指定显示器(Primary、Index(n) 等)。
运行时修改
Window 组件可以在运行时修改。每帧读写 Single<&mut Window> 即可:
rust
fn update_title(mut window: Single<&mut Window>, time: Res<Time>) {
window.title = format!("已运行 {} 秒", time.elapsed().as_secs());
}