How do I convert Twips to Pixels in .NET?

前端 未结 4 1774
渐次进展
渐次进展 2020-12-09 03:12

I\'m working on a migration project in which a database actually stores display sizes in twips. Since I can\'t use twips to assign sizes to WPF or Winforms controls, I was w

4条回答
  •  [愿得一人]
    2020-12-09 03:20

    For reference, another C# version, using the Win32 API instead of requiring a Graphics objects:

    using System.Runtime.InteropServices;
    
    static class SomeUtils {
    
      public static int ConvertTwipsToPixels(int twips, MeasureDirection direction) {
        return (int)(((double)twips)*((double)GetPixperinch(direction))/1440.0);
      }
    
      public static int ConvertPixelsToTwips(int pixels, MeasureDirection direction) {
        return (int)((((double)pixels)*1440.0)/((double)GetPixperinch(direction)));
      }
    
      public static int GetPPI(MeasureDirection direction) {
        int ppi;
        IntPtr dc = GetDC(IntPtr.Zero);
    
        if (direction == MeasureDirection.Horizontal)
          ppi = GetDeviceCaps(dc, 88); //DEVICECAP LOGPIXELSX
        else
          ppi = GetDeviceCaps(dc, 90); //DEVICECAP LOGPIXELSY
    
        ReleaseDC(IntPtr.Zero, dc);
        return ppi;
      }
    
      [DllImport("user32.dll")]
      static extern IntPtr GetDC(IntPtr hWnd);
    
      [DllImport("user32.dll")]
      static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
    
      [DllImport("gdi32.dll")]
      static extern int GetDeviceCaps(IntPtr hdc, int devCap);
    }
    
    public enum MeasureDirection {
      Horizontal,
      Vertical
    }
    

    The MeasureDirection is supposed to be specified as there is no guarantee that pixels are always square (according to the kb).

    Reference: kb210590: ACC2000: How to Convert Twips to Pixels

提交回复
热议问题