c# 刻度:毫米 英寸 像素转换

从目前所掌握的资料来看,c#程序中将毫米转换像素的方法无非两种:

第一种:

   1: /// <summary>
   2: /// 以毫米为单位的显示宽度
   3: /// </summary>
   4: const int HORZSIZE = 4;
   5: /// <summary>
   6: /// 以像素为单位的显示宽度 0~65535
   7: /// </summary>
   8: const int HORZRES = 8;
   9: const int LOGPIXELSX = 88;
  10: const int LOGPIXELSY = 90;
  11: public static double MillimetersToPixelsWidth(IntPtr handle, double length) //length是毫米,1厘米=10毫米
  12: {
  13:     System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(handle);
  14:     IntPtr hdc = g.GetHdc();
  15:     int width = GetDeviceCaps(hdc, HORZSIZE);     // HORZRES 
  16:     int pixels = GetDeviceCaps(hdc, HORZRES);     // BITSPIXEL
  17:     g.ReleaseHdc(hdc);
  18:     return (((double)pixels / (double)width) * (double)length);
  19: }
  20:  
  21: [System.Runtime.InteropServices.DllImport("gdi32.dll")]
  22: private static extern int GetDeviceCaps(IntPtr hdc, int Index);

此种方法计算的值与实际刻度相比:10mm=实际刻度8mm

以此技术的程序:桌面刻度尺

技术文章引用:http://hi.baidu.com/kingcham/item/b3653ce0c69756216dabb8cd

在文章中所说的

GDI中有一个函数是GetDeviceCaps(),可以获取一些关于设备的一些属性,如HORZSIZE/HORZRES/LOGPIXELSX等。
    以上三者的关系通常满足:HORZSIZE = 25.4 * HORZRES/LOGPIXELSX

但是在程序中却无法满足该条件。

第二种:

   1: /// <summary>
   2: /// 1英寸=25.4毫米
   3: /// </summary>
   4: const double millimererTopixel = 25.4;
   5:  
   6: public static double MillimeterToPixel(IntPtr handle, double length) //length是毫米,1厘米=10毫米
   7: {
   8:    System.Windows.Forms.Panel p = new System.Windows.Forms.Panel();
   9:    System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(handle);
  10:  
  11:    //1英寸=25.4mm=96DPI,那么1mm=96/25.4DPI
  12:    return (((double)g.DpiX / millimererTopixel) * (double)length);
  13: }

此种方法是根据网上的换算关系得来的。得到的值与实际刻度相比:180mm=实际刻度185mm

以此技术的程序:夏克屏幕刻度尺

以目前而言,还无法准确的进行转换,从而绘制标准刻度尺。如果各位有更好的方法,还望提示下,先谢谢了。

原文地址:https://www.cnblogs.com/xiaotiannet/p/3520325.html