C#中毫米与像素的换算方法

来源:互联网 发布:mathematica 11.2 mac 编辑:程序博客网 时间:2024/04/30 20:36
      C#中以像素作为尺寸单位,像素是一种相对的尺寸概念,与毫米的转换与当前显示器的分辨率有关。在不同分辨率下转换的系数不同。
借助GDI可以完成毫米至像素的转换。
 
        public static double MillimetersToPixelsWidth(double length)
        {
            System.Windows.Forms.Panel p = new System.Windows.Forms.Panel();
            System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(p.Handle);
            IntPtr hdc = g.GetHdc();
            int width = GetDeviceCaps(hdc, 4);     // HORZRES 
            int pixels = GetDeviceCaps(hdc, 8);     // BITSPIXEL
            g.ReleaseHdc(hdc);
            return (((double)pixels / (double)width) * (double)length);
        }
        [DllImport("gdi32.dll")]
        private static extern int GetDeviceCaps(IntPtr hdc, int Index);
 
像素与毫米的转换
转换还需要知道另一个参数:DPI(每英寸多少点)
象素数 / DPI = 英寸数
英寸数 * 25.4 = 毫米数

对于显示设备,不管是打印机还是屏幕,都有一种通用的方法
先用GetDeviceCaps(设备句柄,LOGPIXELSX)
或者
GetDeviceCaps(设备句柄,LOGPIXELSY)获得设备每英寸的像素数
分别记为:px 和 py
一英寸等于25.4mm
那么毫米换算成像素的公式为 
水平方向的换算: x * px /25.4
垂直方向的换算: y * py /25.4
像素换算为毫米 x * 25.4 / px
在程序中这么写
MyControl.Height := 10{mm} * PixelsPerInch * 10 div 254;
分子和分母同乘以10,将浮点数运算转化为整数运算,效率更高
原创粉丝点击