0
votes

How to find the actual height (and width) of string to be rendered? I need to be able to draw text that is x mm high.

It should be easy to calculate the font size needed if I can get the actual text height.

Eg. start with a font size, measure the rendered text and calculate the new font size (new_font_size = old_font_size * wanted_height / measured_height)

I have tried using Graphics.MeasureString, but that includes some padding which can get quite big for large sizes.

1
Graphics.MeasureString and TextRenderer.MeasureText are the methods I'm familiar with. Both of them measure the actual size of the text and add some margin. Perhaps the MeasureText will give you a more accurate result.Zohar Peled
I need the size without margins.Niklas Björnestål
The "margins" are not actually margins, they are the space needed by the font to display diacritics and descenders. Try it on your own last name :)Hans Passant
Unless the text contains any diacritics or descenders, it shouldn't be included in the size. If I have the text "ABC" and want it 10 mm, I don't want the calculated size to make room for diacritics or descenders.Niklas Björnestål

1 Answers

0
votes

It seems to work to add the text to a GraphicsPath and get the size from the that:

public static SizeF GetSize(String text, Font font, StringFormat format)
{
    GraphicsPath path = new GraphicsPath();
    path.AddString(text, font.FontFamily, (int)font.Style, font.SizeInPoints, new PointF(0, 0), format);
    return path.GetBounds().Size;
}