TextRenderer.MeasureText和Graphics.MeasureString的大小不匹配 [英] TextRenderer.MeasureText and Graphics.MeasureString mismatch in size

查看:955
本文介绍了TextRenderer.MeasureText和Graphics.MeasureString的大小不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是一个舍入问题。区别〜5+像素。

This is not a rounding problem. Difference ~ 5+ pixels.

测试用例字符串:MACD(26,12,9)-0.000016

Test Case String: ""MACD (26,12,9) -0.000016"

e.Graphics.MeasureString("MACD (26,12,9) -0.000016", SystemFonts.DefaultFont).Width)
TextRenderer.MeasureText("MACD (26,12,9) -0.000016", SystemFonts.DefaultFont).Width)

结果总是:结果

139.3942
134

为什么会出现规模如此大的差别?我只需要paint方法外圆串的宽度。但它应该匹配MeasureString,反之亦然。

Why is there so much difference in size? I just need the round of width of string outside paint method. But it should match MeasureString or vice versa.

推荐答案

TextRenderer 使用GDI呈现文本,而图形使用GDI +。两个用于布置文本使大小不同略有不同的方法。

TextRenderer uses GDI to render the text, whereas Graphics uses GDI+. The two use a slightly different method for laying out text so the sizes are different.

哪一个你应该使用取决于什么最终将被用于实际绘制文本。如果您正在使用GDI + Graphics.DrawString 拉它,使用测量 Graphics.MeasureString 。如果您在使用GDI绘图 TextRenderer.DrawText ,使用测量 TextRenderer.MeasureText

Which one you should use depends on what will eventually be used to actually draw the text. If you are drawing it with GDI+ Graphics.DrawString, measure using Graphics.MeasureString. If you are drawing using GDI TextRenderer.DrawText, measure using TextRenderer.MeasureText.

如果该文本将在Windows窗体控件中显示,它使用 TextRenderer 如果 UseCompatibleTextRendering 设置为(这是默认值)。

If the text will be displayed inside a Windows Forms control, it uses TextRenderer if UseCompatibleTextRendering is set to false (which is the default).

你的问题的字里行间,你似乎可以用 TextRenderer ,因为你没有一个图形实例油漆事件之外。如果是这样的话,你可以自己创建一做测量:

Reading between the lines of your question, you seem to be using TextRenderer because you don't have a Graphics instance outside the Paint event. If that's the case, you can create one yourself to do the measuring:

using( Graphics g = someControl.CreateGraphics() )
{
    SizeF size = g.MeasureString("some text", SystemFonts.DefaultFont);
}

如果你没有访问控制来创建你可以用它来创建一个屏幕上,便于测量工作正常图形实例。

If you don't have access to a control to create the graphics instance you can use this to create one for the screen, which works fine for measurement purposes.

using( Graphics g = Graphics.FromHwnd(IntPtr.Zero) )
{
     SizeF size = g.MeasureString("some text", SystemFonts.DefaultFont);
}

这篇关于TextRenderer.MeasureText和Graphics.MeasureString的大小不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆