How can I get the screen resolution using SDL2?

Oxy picture Oxy · Aug 31, 2014 · Viewed 10.9k times · Source

I'm using pixel-perfect source images and SDL2 to make a program. When set to fullscreen, I'd like it to use the native resolution (the SDL_WINDOW_FULLSCREEN_DESKTOP flag) but only between a certain minimum resolution and a reasonable maximum one, after which it will stretch from the largest legal resolution. The problem is that I can only find references to the program's own window or program size on the SDL2 documentation.


Is there any function in SDL from which I could retrieve the screen width and height at least almost directly?

Or I should do something like using SDL_WINDOW_FULLCREEN_DESKTOP and then SDL_GetWindowSize() and resizing the window again? Would this even work as expected? I'd like to fins a more elegant solution than that. It feels dirty.

Answer

Nelfeal picture Nelfeal · Aug 31, 2014

In the SDL 2 wiki, you have a category named Display and Window Management. It lists everything you need to know about SDL 2's management of displays (screens) and windows.

You have multiple choices, the most generic would be using SDL_GetCurrentDisplayMode or SDL_GetDesktopDisplayMode. The difference is explained in the wiki :

There's a difference between SDL_GetDesktopDisplayMode() and SDL_GetCurrentDisplayMode() when SDL runs fullscreen and has changed the resolution. In that case SDL_GetDesktopDisplayMode() will return the previous native display mode, and not the current display mode.

After setting a SDL_DisplayMode with one of these, you can retrieve its attributes w and h.

However, there is another function that might be more appropriate and straightforward : SDL_GetDisplayBounds. If I am not mistaken, it gives you the coordinates of the display relative to the whole set of displays that can be active on the computer, and also the size of the display.

Both methods need you to know the index of the display you want to know about. I have not played that much with this part of SDL 2, but I guess you can use SDL_GetNumVideoDisplays to get the number of displays (and check if there is at least one ? - I think the SDL_Window part might not work if there is no display available anyway) and choose one. Or you could pick the first one, which has index 0.

Oh, and you can look at the exemple on the page of SDL_GetCurrentDisplayMode, they effectively retreive the size of a display.