Search code examples
c#.net-4.5system.drawingmeasurestring

Does/can the Graphics MeasureString method take the width of the container and line wrapping into account?


I have a need to calculate the height of a string given that I already know the width.

For example if have a string like "Curabitur semper ipsum semper nulla dictum, vel vulputate elit fringilla. Donec nec placerat purus, ut blandit lectus. Maecenas non molestie nulla. Class aptent taciti sociosqu."

I can use the following code to calculate the single-line width/height of that string.

using (Graphics gfx = Graphics.FromImage(new Bitmap(1, 1)))
{
    System.Drawing.Font f = new System.Drawing.Font(
        FontFamily.GenericSansSerif, 10, FontStyle.Regular);
    SizeF bounds = gfx.MeasureString(
        message, f, new PointF(0, 0), 
        new StringFormat(StringFormatFlags.MeasureTrailingSpaces));
}

However, what I would like to do is calculate the height of that string if it were within a div of 200px, accounting for line wraps.

At first I thought it was a function of the width of the image used to derive the Graphics object.

using (Graphics gfx = Graphics.FromImage(new Bitmap(500, 200)))

That didn't help and got the same single-line dimensions.

Does anyone know of any other tricks to get this?


Solution

  • It sounds like you need to account for the WordBreak flag:

    int h = 0;
    using (Graphics g = CreateGraphics()) {
      using (Font f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular)) {
        h = TextRenderer.MeasureText(msg, f, new Size(200, 0), 
                                     TextFormatFlags.WordBreak).Height;
      }
    }