为什么TextRenderer.MeasureText不能在C#中使用较大的字体正确测量文本?

我正在做的是获取字符串的像素大小并将其转换为百分之一英寸(即像素/ DPI =英寸,英寸* 100 =百分之一英寸)。 这是我的代码:

private static SizeF TextSize(string text, Font txtFnt) { SizeF txtSize = new SizeF(); // The size returned is 'Size(int width, int height)' where width and height // are the dimensions of the string in pixels Size s = System.Windows.Forms.TextRenderer.MeasureText(text, txtFnt); // Value based on normal DPI settings of 96 txtSize.Width = (float)Math.Ceiling((float)s.Width / 96f * 100f); txtSize.Height = (float)Math.Ceiling((float)s.Height / 96f * 100f); return txtSize; } 

现在,使用Arial字体,这对于小于12的字体都可以正常工作,但之后字符开始被切断,因为计算出的尺寸小于实际尺寸。 我知道我的DPI设置设置为96.我的字体定义与字体大小的变化相同:

 Font myFont = new Font("Arial", , FontStyle.Regular, GraphicsUnit.Point); 

我相信我必须使用GraphicsUnit.Point因为我正在绘制字符串的自定义控件,但GraphicsUnit重要?

MeasureText函数是否正常工作,还是还有其他事情发生?

编辑

我正在绘制自定义打印预览控件。 打印预览控件中的单位为“英寸/ 100”(因此转换)。 我相信文本,图像等是用Printer图形对象绘制的,但我不完全确定。

很久以前我遇到了类似的问题,特别是测量文本INSIDE文本框。 问题的关键在于:绘制文本有两种主要方式。 Win32 API和System.Drawing。 如果您尝试在文本框中测量文本,它将使用Win32 API绘制,您还需要使用Win32 API进行测量。 如果您测量System.Drawing绘制的文本,那么使用.net的测量将匹配。

基本上,Forms文本框使用Win32 API进行布局和绘制,测量也需要来自Win32。

你没有说明你在具体测量什么,在哪里,所以这个答案甚至可能都不适用。

选项有所不同,字体越大,影响越大。 以下是最适合我们的设置 – 您的里程可能会有所不同。 (代码很奇怪,因为我们在J#中使用它):

 private static System.Drawing.StringFormat createStringFormat() { System.Drawing.StringFormat fmt = new System.Drawing.StringFormat (System.Drawing.StringFormat.get_GenericTypographic()); fmt.set_Trimming(System.Drawing.StringTrimming.None); fmt.set_FormatFlags(System.Drawing.StringFormatFlags.MeasureTrailingSpaces | System.Drawing.StringFormatFlags.NoWrap); return fmt; } 

字体提示。

Windows使用的字体被暗示,这意味着它们可能不完全是字体指定的大小。

http://blogs.msdn.com/b/cjacks/archive/2006/05/11/595525.aspx