Calculating the minimum width required to display text in X-lines in .Net?

How would you calculate the minimum width required to display a line in X-lines, given that the text should be split into spaces?

0


source to share


2 answers


Possible hint: Perhaps some kind of binary search using Graphics.MeasureString ()?



+1


source


Edit: Didn't realize you want to try and fit the text to a fixed number of lines. It was not easy to try and resolve. This is the best I could think of, 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;
}

      



Usage example:

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);

      

0


source







All Articles