Last night I had cause to measure the rendered dimensions of a string at a given font and width. Without going to much into the why, let's just say if you need to do this you're either doing custom text rendering, or, in my case, positioning report elements relatively in a report suite that doesn't update Control.Height except in some magical layout land that you can't figure out how to access. To get around the problem, I came up with this:

private int MeasureStringHeight(int width, string textToMeasure, Font font)
{
    Bitmap bmp = new Bitmap(1,1);
    Graphics g = Graphics.FromImage(bmp);
    SizeF bounds = g.MeasureString(textToMeasure, font, width);
    int height = Convert.ToInt32(bounds.Height);
    //This part is to convert pixels to inches, which is what I needed.
    //You could just return height for pixels

    return height/g.DpiY;
}

This is not 100% precise, but close enough for probably most needs. If you need a more accurate height, have a look at Graphics.MeasureCharacterRanges.  Additionally, since I'm converting the more precise Float value to an int, and then further converting it to inches, you end up losing several points of precision, but this was my need. You could always just get the SizeF and go from there to be as precise as possible.

There are also several overloads available for MeasureString that will allow you to not specify the width, or specify a bounded rendering area.

Hope it helps someone.

Tags: