Question

Because of lack of Graphics object in certain places in my application, I decided to use TextRenderer class. What is quite surprising though is that it adds a lot of margins to measured text. For example:

private void button1_Click(object sender, EventArgs e) {

    using (var g = this.CreateGraphics()) {

        Font font = new Font("Calibri", 20.0f, GraphicsUnit.Pixel);
        Size size = TextRenderer.MeasureText("Ala ma kota", font);

        g.DrawRectangle(Pens.Red, new Rectangle(new Point(10, 10), size));
        TextRenderer.DrawText(g, "Ala ma kota", font, new Point(10, 10), Color.Black);
    }
}

Gives the following result:

Text with margins

Why does it do so? Is there a way to force it to get the real text size? (and of course draw it in the same rectangle it returns)

Was it helpful?

Solution

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 of DrawText and MeasureText that take a Size and TextFormatFlags 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 a TextFormatFlags value of NoPadding or LeftAndRightPadding. If you are specifying a padding value other than the default, you should use the overload of MeasureText(IDeviceContext, String, Font, Size, TextFormatFlags) that takes a IDeviceContext 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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top