From MSDN:
For example, the default behavior of the
TextRenderer
is to add padding to the bounding rectangle of the drawn text to accommodate overhanging glyphs. If you need to draw a line of text without these extra spaces, use the versions ofDrawText
andMeasureText
that take aSize
andTextFormatFlags
parameter, as shown in the example.
You must also pass the Graphics
object for correct results, because:
This overload of
MeasureText(String, Font, Size, TextFormatFlags)
will ignore aTextFormatFlags
value ofNoPadding
orLeftAndRightPadding
. If you are specifying a padding value other than the default, you should use the overload ofMeasureText(IDeviceContext, String, Font, Size, TextFormatFlags)
that takes aIDeviceContext
object.
Size size = TextRenderer.MeasureText(g,
"Ala ma kota",
font,
new Size(int.MaxValue, int.MaxValue),
TextFormatFlags.NoPadding);
TextRenderer.DrawText(g, "Ala ma kota", font,
new Point(10, 10),
Color.Black,
TextFormatFlags.NoPadding);
g.DrawRectangle(Pens.Red, new Rectangle(new Point(10, 10), size));
Also have a look at using the Graphics
methods directly: GDI+ MeasureString() is incorrectly trimming text