Understanding Screen Coordinates and Pixels in SDL2
What exactly is a "screen coordinate"? Is it always the same as a pixel?
In SDL, when you specify positions (like for SDL_CreateWindow()
) or dimensions, you use units called screen coordinates. These are part of SDL's abstraction layer, designed to provide a consistent way to reason about layout across different displays and platforms.
On many traditional displays, one screen coordinate unit directly corresponds to one physical pixel on the screen. If you create a window 800 units wide, it will occupy 800 physical pixels horizontally.
// Creates a window typically 800 physical pixels wide
// on a standard density display.
SDL_CreateWindow(
"My Window",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
800, 600, // Width and Height in Screen Coordinates
0
);
High DPI Displays
The distinction becomes important with the rise of High DPI (Dots Per Inch) displays, sometimes marketed as "Retina" displays. These screens pack more physical pixels into the same physical area compared to older displays.
On a High DPI display, the operating system often uses scaling. This means that UI elements are rendered using more physical pixels to keep their physical size consistent and readable. For example, a button might use a 2x2 block of physical pixels for every 1x1 block it would have used on a standard display.
SDL interacts with this OS-level scaling. On such displays, one SDL screen coordinate might map to multiple physical pixels (e.g., 1 screen coordinate = 2 horizontal pixels, or 1 screen coordinate = 1.5 horizontal pixels).
The benefit of using screen coordinates is that you can often design your UI layout using these abstract units, and SDL (in conjunction with the OS) handles the conversion to the appropriate number of physical pixels, making your application look correctly sized across different display densities.
You generally don't need to worry about the exact mapping unless you are doing very low-level pixel manipulation or need fine control over rendering based on the physical pixel density.
We cover display scaling, DPI, and how to query the relationship between screen coordinates and pixels in more detail in a later lesson dedicated to rendering and display properties.
Creating a Window
Learn how to create and customize windows, covering initialization, window management, and rendering