dpi.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #include "main.h"
  2. #include "dpi.h"
  3. // DPI awareness based on http://msdn.microsoft.com/en-US/library/dd464660.aspx
  4. // Definition: relative pixel = 1 pixel at 96 DPI and scaled based on actual DPI.
  5. BOOL _fInitialized = FALSE;
  6. int _dpiX = 96, _dpiY = 96;
  7. void _Init()
  8. {
  9. if (!_fInitialized)
  10. {
  11. HDC hdc = GetDC(NULL);
  12. if (hdc)
  13. {
  14. _dpiX = GetDeviceCaps(hdc, LOGPIXELSX);
  15. _dpiY = GetDeviceCaps(hdc, LOGPIXELSY);
  16. ReleaseDC(NULL, hdc);
  17. }
  18. _fInitialized = TRUE;
  19. }
  20. }
  21. // Get screen DPI.
  22. int GetDPIX()
  23. {
  24. _Init();
  25. return _dpiX;
  26. }
  27. int GetDPIY()
  28. {
  29. _Init();
  30. return _dpiY;
  31. }
  32. // Convert between raw pixels and relative pixels.
  33. int ScaleX(int x)
  34. {
  35. _Init();
  36. return MulDiv(x, _dpiX, 96);
  37. }
  38. int ScaleY(int y)
  39. {
  40. _Init();
  41. return MulDiv(y, _dpiY, 96);
  42. }
  43. int UnscaleX(int x)
  44. {
  45. _Init();
  46. return MulDiv(x, 96, _dpiX);
  47. }
  48. int UnscaleY(int y)
  49. {
  50. _Init();
  51. return MulDiv(y, 96, _dpiY);
  52. }
  53. int _ScaledSystemMetricX(int nIndex)
  54. {
  55. _Init();
  56. return MulDiv(GetSystemMetrics(nIndex), 96, _dpiX);
  57. }
  58. int _ScaledSystemMetricY(int nIndex)
  59. {
  60. _Init();
  61. return MulDiv(GetSystemMetrics(nIndex), 96, _dpiY);
  62. }
  63. // Determine the screen dimensions in relative pixels.
  64. int ScaledScreenWidth()
  65. {
  66. return _ScaledSystemMetricX(SM_CXSCREEN);
  67. }
  68. int ScaledScreenHeight()
  69. {
  70. return _ScaledSystemMetricY(SM_CYSCREEN);
  71. }
  72. // Scale rectangle from raw pixels to relative pixels.
  73. void ScaleRect(__inout RECT *pRect)
  74. {
  75. pRect->left = ScaleX(pRect->left);
  76. pRect->right = ScaleX(pRect->right);
  77. pRect->top = ScaleY(pRect->top);
  78. pRect->bottom = ScaleY(pRect->bottom);
  79. }
  80. // Determine if screen resolution meets minimum requirements in relative pixels.
  81. BOOL IsResolutionAtLeast(int cxMin, int cyMin)
  82. {
  83. return (ScaledScreenWidth() >= cxMin) && (ScaledScreenHeight() >= cyMin);
  84. }
  85. // Convert a point size (1/72 of an inch) to raw pixels.
  86. int PointsToPixels(int pt)
  87. {
  88. _Init();
  89. return MulDiv(pt, _dpiY, 72);
  90. }