Search code examples
rustwindowresolution

How do I get the screen / display resolution?


I am currently working on a game in Rust (Piston Crate) and I want to center the Window it creates. It allows me to change the window's offset from the top left of the screen. I want to get the resolution the operating system works in (screen / display / monitor resolution) and center the window based on that.

In Python for example, by using pyautogui, you can get the screen resolution using pyautogui.size().

In Java, by using java.awt, you can get the screen resolution using Toolkit.getDefaultToolkit().getScreenSize().

Is there something similar in Rust I could use? (std- or any extern crate)


Solution

  • I depends of the backend you use. For example if you use the Winit / Glutin backend you can use the MonitorHandle struct, which has a size() method.

    Docs:https://docs.rs/winit/0.26.1/winit/monitor/struct.MonitorHandle.html

    or for Glutin https://docs.rs/glutin/0.28.0/glutin/window/struct.Window.html#method.available_monitors

    The Glutin module also has a dpi module that can provide information. https://docs.rs/glutin/0.28.0/glutin/dpi/index.html

    If you use SDL2 backend, you could take a look at the sdl2_sys module SDL_HINT_RENDER_LOGICAL_SIZE https://docs.rs/sdl2-sys/0.35.2/sdl2_sys/constant.SDL_HINT_RENDER_LOGICAL_SIZE_MODE.html