Managing Different Aspect Ratios
What happens if a player has a monitor with a different aspect ratio than our game's resolution?
When your game's aspect ratio doesn't match the monitor's, SDL handles it by either adding black bars (letterboxing/pillarboxing) or stretching the content. Here's how different scenarios are handled.
Desktop Fullscreen
In desktop fullscreen mode, SDL maintains your game's aspect ratio by default. If your game renders at 1920x1080 (16:9) but the monitor is 2560x1440 (16:9), SDL scales the content proportionally. However, if the monitor is 1920x1200 (16:10), SDL adds black bars at the top and bottom.
Here's how to detect the display's aspect ratio:
#include <SDL.h>
#include <iostream>
void CheckAspectRatio(SDL_Window* Window) {
// Get display bounds
SDL_Rect DisplayBounds;
int DisplayIndex{
SDL_GetWindowDisplayIndex(Window)};
SDL_GetDisplayBounds(DisplayIndex,
&DisplayBounds);
// Calculate aspect ratios
float DisplayRatio{
static_cast<float>(DisplayBounds.w) /
DisplayBounds.h
};
int GameWidth, GameHeight;
SDL_GetWindowSize(Window, &GameWidth,
&GameHeight);
float GameRatio{
static_cast<float>(GameWidth) / GameHeight};
std::cout << "Display ratio: " << DisplayRatio
<< "\nGame ratio: " << GameRatio << "\n";
if (DisplayRatio > GameRatio) {
std::cout <<
"Black bars will appear on the sides\n";
} else if (DisplayRatio < GameRatio) {
std::cout <<
"Black bars will appear on top/bottom\n";
}
}
Exclusive Fullscreen
In exclusive fullscreen, the monitor changes its resolution to match your game. However, if the aspect ratios don't match, you'll need to decide how to handle it:
#include <SDL.h>
void ConfigureAspectRatio(SDL_Window* Window,
bool PreserveRatio) {
if (PreserveRatio) {
// Add letterboxing/pillarboxing
SDL_RenderSetLogicalSize(
SDL_GetRenderer(Window), 1920, 1080);
} else {
// Stretch to fill
SDL_RenderSetScale(SDL_GetRenderer(Window),
1.0f, 1.0f);
}
}
Most games provide options for how to handle aspect ratio differences, letting players choose between preserving the aspect ratio with black bars or stretching to fill the screen.
Fullscreen Windows
Learn how to create and manage fullscreen windows in SDL, including desktop and exclusive fullscreen modes.