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.
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
.
If the text will be displayed inside a Windows Forms control, it uses TextRenderer
if UseCompatibleTextRendering
is set to false
(which is the default).
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);
}