Take the 2-minute tour ×

I'm trying to create an image with some text on it and I want the image's size to match the size of the rendered text.

When I use System.Windows.Forms.TextRenderer.MeasureText(...) to measure the text, I get dimensions that include font padding. When the text is rendered, it seems to use the same padding.

Is there any way to determine the size of a string of text and then render it without any padding?

This is the code I've tried:

// Measure the text dimensions
var text = "Hello World";
var fontFamily = new Font("Arial", 30, FontStyle.Regular);
var textColor = new SolidBrush(Color.Black);
Size textSize = TextRenderer.MeasureText(text, fontFamily, 
                             Size.Empty, TextFormatFlags.NoPadding);

// Render the text with the given dimensions
Bitmap bmp = new Bitmap(textSize.Width, textSize.Height);
Graphics g = Graphics.FromImage(bmp);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.DrawString(text, fontFamily, textColor, new PointF(0, 0));            
bmp.Save("output.png", ImageFormat.Png);

This is what currently gets rendered out:

Current Output

This is what I want to render:

Desired Output

I also looked into Graphics.MeasureString(...), but that can only be used on an existing Graphics object. I want to know the size before creating the image. Also, calling Graphics.MeasureString(...) returns the same dimensions, so it doesn't help me any.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

I think it is because the font height is 46 for 30point font.
This is so you can have special uppercase characters (ÉÖÄÅ) and lover case characters(gqp).
The leading and trailing blank spaces probably also have some thing to do with this.

share|improve this answer
That was it! i.imgur.com/Py4zK.png –  Dan Herbert Apr 21 '10 at 11:17

Your Answer


