How to change window size at runtime using Rust and SDL2?

80 Views Asked by At

I want to, eventually, make a graphics menu for a game in which among other things the user should be able to switch the game windows's resolution. What would be the correct way of going about doing this?

For instance, using the example from the sdl2 crate's "getting started" section:

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));
    }
}

I'd ideally like to, at any point during the loop, be able to change the resolution from 800x600 to some arbitrary value - say, 1280x720 - while keeping the "game state" intact (in this example, that'd just be the value of i).

1

There are 1 best solutions below

0
Dynastray On

You can convert you canvas back to a Window, &Window, &mut Window.

As mentioned in the documentation of SDL2 [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));
}