views:

221

answers:

2

How could you calculate the minimum width needed to display a string in X lines, given that text should break on whitespace?

+1  A: 

Possible Hint: Perhaps some sort of binary search using Graphics.MeasureString()?

Adam Tegen
A: 

Edit: Didn't realize you wanted to try and fit the text to a fixed number of lines. This was a tough one to try and solve. This is the best I could come up with and may not be the most elegant, but it seems to work:

public SizeF CalculateWidth(Font font, Graphics graphics, int numOfLines,
                            string text)
{
    SizeF sizeFull = graphics.MeasureString(text, font,
                                            new SizeF(
                                                float.PositiveInfinity,
                                                float.PositiveInfinity),
                                            StringFormat.
                                                GenericTypographic);

    float width = sizeFull.Width/numOfLines;
    float averageWidth = sizeFull.Width/text.Length;
    int charsFitted;
    int linesFilled;

    SizeF needed = graphics.MeasureString(text, font,
                                          new SizeF(width,
                                                    float.
                                                        PositiveInfinity),
                                          StringFormat.
                                              GenericTypographic,
                                          out charsFitted,
                                          out linesFilled);

    while (linesFilled > numOfLines)
    {
        width += averageWidth;
        needed = graphics.MeasureString(text, font,
                                        new SizeF(width,
                                                  float.PositiveInfinity),
                                        StringFormat.GenericTypographic,
                                        out charsFitted, out linesFilled);
    }

    return needed;
}

Example usage:

Font font = new Font("Arial", 12, FontStyle.Regular,
                     GraphicsUnit.Pixel);
Graphics g = Graphics.FromImage(new Bitmap(1, 1));
string text = "Some random text with words in it.";

SizeF size = CalculateWidth(font, g, 3, text);
duckworth
That would be assuming you only wanted 1 word on a line.
Adam Tegen