-
[C#] cm <-> pixel 변환, DPI 구하기Microsoft .NET/C# 2019. 4. 2. 10:30
DPI 활용 방향
디스플레이에 출력되는 물체의 크기가 실제 크기와 동일해야 하는 경우 DPI를 사용하여 CM를 PIXEL로 변환하여 출력
C#에서 DPI 구하기
public class ScreenInformations { public static uint RawDpi { get; private set; } static ScreenInformations() { uint dpiX; uint dpiY; GetDpi(DpiType.RAW, out dpiX, out dpiY); RawDpi = dpiX; } /// <summary> /// Returns the scaling of the given screen. /// </summary> /// <param name="dpiType">The type of dpi that should be given back..</param> /// <param name="dpiX">Gives the horizontal scaling back (in dpi).</param> /// <param name="dpiY">Gives the vertical scaling back (in dpi).</param> private static void GetDpi(DpiType dpiType, out uint dpiX, out uint dpiY) { var point = new System.Drawing.Point(1, 1); var hmonitor = MonitorFromPoint(point, _MONITOR_DEFAULTTONEAREST); switch (GetDpiForMonitor(hmonitor, dpiType, out dpiX, out dpiY).ToInt32()) { case _S_OK: return; case _E_INVALIDARG: throw new ArgumentException("Unknown error. See https://msdn.microsoft.com/en-us/library/windows/desktop/dn280510.aspx for more information."); default: throw new COMException("Unknown error. See https://msdn.microsoft.com/en-us/library/windows/desktop/dn280510.aspx for more information."); } } //https://msdn.microsoft.com/en-us/library/windows/desktop/dd145062.aspx [DllImport("User32.dll")] private static extern IntPtr MonitorFromPoint([In]System.Drawing.Point pt, [In]uint dwFlags); //https://msdn.microsoft.com/en-us/library/windows/desktop/dn280510.aspx [DllImport("Shcore.dll")] private static extern IntPtr GetDpiForMonitor([In]IntPtr hmonitor, [In]DpiType dpiType, [Out]out uint dpiX, [Out]out uint dpiY); const int _S_OK = 0; const int _MONITOR_DEFAULTTONEAREST = 2; const int _E_INVALIDARG = -2147024809; } /// <summary> /// Represents the different types of scaling. /// </summary> /// <seealso cref="https://msdn.microsoft.com/en-us/library/windows/desktop/dn280511.aspx"/> public enum DpiType { EFFECTIVE = 0, ANGULAR = 1, RAW = 2, }
1 dpi == 0.393701px
CM -> PIXEL 변환 공식
dpi * (1 dpi) * cm = px
PIXEL -> CM 변환 공식
dpi * (1 dpi) / px = cm
결과 확인용 엑셀 문서
'Microsoft .NET > C#' 카테고리의 다른 글
[C#] C#에서 Python 코드 사용하기 (함수, 클래스) (0) 2019.04.11 [C#] 널 결합 연산자 (Null Coalesce Operator) (0) 2019.04.10 [C#] 조건부 컴파일 기호, 여러 개(코드 비활성화, 코드 숨기기, #if, #else, #endif) (0) 2019.03.21 [C#] cm <-> pixel 변환, DPI 구하기 (0) 2019.03.06 [C#] #if, #else, #endif (Debug or Release에서 동작하는 코드 만들기) (0) 2019.03.06