views:

36

answers:

1

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.

+1  A: 

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.

Jens Granlund
That was it! http://i.imgur.com/Py4zK.png
Dan Herbert