How can I get the dimensions of a drawn string without padding?

Posted by Dan Herbert on Stack Overflow See other posts from Stack Overflow or by Dan Herbert
Published on 2010-04-21T00:38:18Z Indexed on 2010/04/21 3:33 UTC
Read the original article Hit count: 367

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about c#2.0

Related posts about .NET