Handling Different Screen Resolutions in SDL2
What's the best way to handle different screen resolutions in my SDL2 game?
Handling different screen resolutions is crucial for creating a game that looks good on various devices. Here's a strategy you can use:
Define a Base Resolution
First, decide on a base resolution for your game. This is the resolution you'll use for designing your game's layout and assets. For example, let's say we choose 1280x720 as our base resolution.
Calculate a Scaling Factor
When your game starts, calculate a scaling factor based on the actual screen resolution:
#include <SDL.h>
#include <iostream>
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_DisplayMode dm;
if (SDL_GetCurrentDisplayMode(0, &dm) != 0) {
std::cout <<
"SDL_GetCurrentDisplayMode failed: " <<
SDL_GetError() << "\n";
return 1;
}
const int BASE_WIDTH = 1280;
const int BASE_HEIGHT = 720;
float scaleX = dm.w / static_cast<float>(
BASE_WIDTH);
float scaleY = dm.h / static_cast<float>(
BASE_HEIGHT);
float scale = std::min(scaleX, scaleY);
std::cout << "Screen resolution: " << dm.w <<
"x" << dm.h << "\n";
std::cout << "Scaling factor: " << scale <<
"\n";
SDL_Quit();
return 0;
}
Apply the Scaling Factor
Use this scaling factor when rendering your game elements. You can create a utility function to scale positions and sizes:
SDL_Rect ScaleRect(const SDL_Rect& rect,
float scale) {
return SDL_Rect{
static_cast<int>(rect.x * scale),
static_cast<int>(rect.y * scale),
static_cast<int>(rect.w * scale),
static_cast<int>(rect.h * scale)};
}
Render at Native Resolution
Create your SDL window at the native screen resolution, but render your game elements using the scaled positions and sizes:
SDL_Window* window =
SDL_CreateWindow("Game",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
dm.w, dm.h,
SDL_WINDOW_FULLSCREEN);
// In your render loop:
SDL_Rect baseRect{100, 100, 200, 200};
SDL_Rect scaledRect =
ScaleRect(baseRect, scale);
SDL_RenderFillRect(renderer, &scaledRect);
By following this approach, your game will maintain its relative layout across different screen resolutions while taking advantage of the full screen real estate available.
Image Scaling and Aspect Ratios
Learn techniques for scaling images and working with aspect ratios