C#中以像素作為尺寸單位,像素是一種相對的尺寸概念,與毫米的轉(zhuǎn)換與當前顯示器的分辨率有關(guān)。在不同分辨率下轉(zhuǎn)換的系數(shù)不同。
借助GDI可以完成毫米至像素的轉(zhuǎn)換。
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);
像素與毫米的轉(zhuǎn)換
轉(zhuǎn)換還需要知道另一個參數(shù):DPI(每英寸多少點)
象素數(shù) / DPI = 英寸數(shù)
英寸數(shù) * 25.4 = 毫米數(shù)
對于顯示設備,不管是打印機還是屏幕,都有一種通用的方法
先用GetDeviceCaps(設備句柄,LOGPIXELSX)或者 GetDeviceCaps(設備句柄,LOGPIXELSY)獲得設備每英寸的像素數(shù)
分別記為: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,將浮點數(shù)運算轉(zhuǎn)化為整數(shù)運算,效率更高
新聞熱點
疑難解答