DPI.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #pragma once
  2. // Definition: relative pixel = 1 pixel at 96 DPI and scaled based on actual DPI.
  3. class CDPI
  4. {
  5. public:
  6. CDPI() : _fInitialized(false), _dpiX(96), _dpiY(96) { }
  7. // Get screen DPI.
  8. int GetDPIX() { _Init(); return _dpiX; }
  9. int GetDPIY() { _Init(); return _dpiY; }
  10. // Convert between raw pixels and relative pixels.
  11. int ScaleX(int x) { _Init(); return MulDiv(x, _dpiX, 96); }
  12. int ScaleY(int y) { _Init(); return MulDiv(y, _dpiY, 96); }
  13. int UnscaleX(int x) { _Init(); return MulDiv(x, 96, _dpiX); }
  14. int UnscaleY(int y) { _Init(); return MulDiv(y, 96, _dpiY); }
  15. // Determine the screen dimensions in relative pixels.
  16. int ScaledScreenWidth() { return _ScaledSystemMetricX(SM_CXSCREEN); }
  17. int ScaledScreenHeight() { return _ScaledSystemMetricY(SM_CYSCREEN); }
  18. // Scale rectangle from raw pixels to relative pixels.
  19. void ScaleRect(__inout RECT *pRect)
  20. {
  21. pRect->left = ScaleX(pRect->left);
  22. pRect->right = ScaleX(pRect->right);
  23. pRect->top = ScaleY(pRect->top);
  24. pRect->bottom = ScaleY(pRect->bottom);
  25. }
  26. // Determine if screen resolution meets minimum requirements in relative
  27. // pixels.
  28. bool IsResolutionAtLeast(int cxMin, int cyMin)
  29. {
  30. return (ScaledScreenWidth() >= cxMin) && (ScaledScreenHeight() >= cyMin);
  31. }
  32. // Convert a point size (1/72 of an inch) to raw pixels.
  33. int PointsToPixels(int pt) { _Init(); return MulDiv(pt, _dpiY, 72); }
  34. // Invalidate any cached metrics.
  35. void Invalidate() { _fInitialized = false; }
  36. private:
  37. void _Init()
  38. {
  39. if (!_fInitialized)
  40. {
  41. HDC hdc = GetDC(NULL);
  42. if (hdc)
  43. {
  44. _dpiX = GetDeviceCaps(hdc, LOGPIXELSX);
  45. _dpiY = GetDeviceCaps(hdc, LOGPIXELSY);
  46. ReleaseDC(NULL, hdc);
  47. }
  48. _fInitialized = true;
  49. }
  50. }
  51. int _ScaledSystemMetricX(int nIndex)
  52. {
  53. _Init();
  54. return MulDiv(GetSystemMetrics(nIndex), 96, _dpiX);
  55. }
  56. int _ScaledSystemMetricY(int nIndex)
  57. {
  58. _Init();
  59. return MulDiv(GetSystemMetrics(nIndex), 96, _dpiY);
  60. }
  61. private:
  62. bool _fInitialized;
  63. int _dpiX;
  64. int _dpiY;
  65. };