代码之家  ›  专栏  ›  技术社区  ›  Adam Tegen

计算在.Net中以X行显示文本所需的最小宽度?

  •  0
  • Adam Tegen  · 技术社区  · 16 年前

    考虑到文本应该以空白分隔,如何计算以X行显示字符串所需的最小宽度?

    2 回复  |  直到 16 年前
        1
  •  1
  •   Adam Tegen    16 年前

    可能的提示:也许是某种使用Graphics.MeasureString()的二进制搜索?

        2
  •  0
  •   John Lemp Chris Heald    16 年前

    编辑:

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

    示例用法:

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