DPI.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. int PixelsToPoints(int px) { _Init(); return MulDiv(px, 72, _dpiY); }
  35. // Invalidate any cached metrics.
  36. void Invalidate() { _fInitialized = false; }
  37. private:
  38. void _Init()
  39. {
  40. if (!_fInitialized)
  41. {
  42. HDC hdc = GetDC(NULL);
  43. if (hdc)
  44. {
  45. _dpiX = GetDeviceCaps(hdc, LOGPIXELSX);
  46. _dpiY = GetDeviceCaps(hdc, LOGPIXELSY);
  47. ReleaseDC(NULL, hdc);
  48. }
  49. _fInitialized = true;
  50. }
  51. }
  52. int _ScaledSystemMetricX(int nIndex)
  53. {
  54. _Init();
  55. return MulDiv(GetSystemMetrics(nIndex), 96, _dpiX);
  56. }
  57. int _ScaledSystemMetricY(int nIndex)
  58. {
  59. _Init();
  60. return MulDiv(GetSystemMetrics(nIndex), 96, _dpiY);
  61. }
  62. private:
  63. bool _fInitialized;
  64. int _dpiX;
  65. int _dpiY;
  66. };