如何使用Rust和SDL2在运行时更改窗口大小?

y4ekin9u  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(118)

我想,最终,为游戏制作一个图形菜单,其中用户应该能够切换游戏窗口的分辨率。什么是正确的方法来做到这一点?
例如,使用sdl 2 crate的“入门”部分中的示例:

extern crate sdl2;

use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use std::time::Duration;

pub fn main() {
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();

    let window = video_subsystem.window("rust-sdl2 demo", 800, 600)
        .position_centered()
        .build()
        .unwrap();

    let mut canvas = window.into_canvas().build().unwrap();

    canvas.set_draw_color(Color::RGB(0, 255, 255));
    canvas.clear();
    canvas.present();
    let mut event_pump = sdl_context.event_pump().unwrap();
    let mut i = 0;
    'running: loop {
        i = (i + 1) % 255;
        canvas.set_draw_color(Color::RGB(i, 64, 255 - i));
        canvas.clear();
        for event in event_pump.poll_iter() {
            match event {
                Event::Quit {..} |
                Event::KeyDown { keycode: Some(Keycode::Escape), .. } => {
                    break 'running
                },
                _ => {}
            }
        }

        canvas.present();
        ::std::thread::sleep(Duration::new(0, 1_000_000_000u32 / 60));
    }
}

字符串
理想情况下,在循环过程中的任何时候,我都希望能够将分辨率从800 x600更改为某个任意值-比如1280 x720-同时保持“游戏状态”不变(在本例中,这只是i的值)。

noj0wjuj

noj0wjuj1#

您可以将画布转换回Window,&Window,&mut Window。
如SDL 2文档中所述[https://docs.rs/sdl2/latest/sdl2/render/type.WindowCanvas.html]

let mut canvas = window.into_canvas().build().unwrap();

'running: loop {
    canvas.clear();
    for event in event_pump.poll_iter() {
        match event {
            Event::Quit { .. } => {
                break 'running;
            },
            Event::KeyDown { keycode: Some(key), .. } => {
                match key {
                    Keycode::F11 => { 
                        let _ = canvas.window_mut().set_size(1920, 1080);
                        let _ = canvas.window_mut().set_fullscreen(sdl2::video::FullscreenType::Desktop);
                }
                    _ => {}
                };
            }
            _ => {}
        }
    }

    canvas.present();
    ::std::thread::sleep(::std::time::Duration::new(0, 1_000_000_000u32 / 60));
}

字符串

相关问题