开发者

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

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:

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

This is what I want to render:

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

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜