Pixel Density and High-DPI Displays

DPI Scale Calculation

In GetDPIScale(), why do we only use the width to calculate the scale? What about height?

Abstract art representing computer programming

The decision to use only width for DPI scale calculation is based on how modern displays and operating systems handle DPI scaling. Let's explore why this works and when you might need to consider both dimensions.

Why Width is Usually Sufficient

Most modern displays maintain consistent DPI scaling across both dimensions. Here's how we can verify this:

#include <SDL.h>
#include <iostream>

void CheckScaling(SDL_Window* Window) {
  int w1, h1, w2, h2;
  SDL_GetWindowSize(Window, &w1, &h1);
  SDL_GetWindowSizeInPixels(Window, &w2, &h2);

  float ScaleX{float(w2) / w1};
  float ScaleY{float(h2) / h1};

  std::cout << "Scale X: " << ScaleX << "\n"
            << "Scale Y: " << ScaleY << "\n";
}

int main() {
  SDL_Init(SDL_INIT_VIDEO);
  SDL_Window* Window{SDL_CreateWindow(
    "Scale Test",
    SDL_WINDOWPOS_UNDEFINED,
    SDL_WINDOWPOS_UNDEFINED,
    800, 600, 0)};

  CheckScaling(Window);

  SDL_DestroyWindow(Window);
  SDL_Quit();
  return 0;
}

On a typical 125% DPI scale, you'll see:

Scale X: 1.25
Scale Y: 1.25

When to Consider Both Dimensions

However, there are cases where you might want to check both dimensions:

  • Non-square pixel displays (rare in modern systems)
  • Custom scaling settings
  • Platform-specific quirks

Here's an improved version of GetDPIScale():

struct Scale2D {
  float X, Y;
};

Scale2D GetDPIScale2D(SDL_Window* Window) {
  int w1, h1, w2, h2;
  SDL_GetWindowSize(Window, &w1, &h1);
  SDL_GetWindowSizeInPixels(Window, &w2, &h2);

  return Scale2D{
    float(w2) / w1,
    float(h2) / h1
  };
}

void HandleDifferentScales(SDL_Window* Window) {
  Scale2D Scale{GetDPIScale2D(Window)};
  if (std::abs(Scale.X - Scale.Y) > 0.01f) {
    std::cout << "Warning: Non-uniform "
      "scaling detected\n";
  }
}

In practice, using width alone is usually sufficient because:

  • Operating systems maintain uniform scaling
  • Different X/Y scales can cause visual problems
  • Most UI frameworks assume uniform scaling

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 71 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved