TextRenderer.MeasureText()和文本框最大文本长度

时间:2014-10-08 06:50:15

标签: c# .net textbox textrenderer

我有一个很长的字符串(~100k个字符)。我需要知道这个字符串的长度。我打电话给

Size s = TextRenderer.MeasureText(graphics, text, font);

但它返回宽度等于7.只有当文本长度< = 43679时,它才会返回正确的值!

另外,如果我在文本框中插入文本,则文本框中不会显示该文本!我可以用鼠标选择文本,通过“Ctrl + C”复制,但文本不可见。 MaxLength 属性超过文本长度。

我查看了msdn,但没有找到有关MeasureText和TextBox中使用的最大文本长度的任何信息。

我可以找到有关此文档的文档?有没有办法增加最大文本长度?这些值是否取决于操作系统和计算机性能?

2 个答案:

答案 0 :(得分:0)

尝试使用此代码测量字符串,textrenderer不准确

protected int _MeasureDisplayStringWidth ( Graphics graphics, string text, Font font )
{
    if ( text == "" )
        return 0;

    StringFormat format = new StringFormat ( StringFormat.GenericDefault );
    RectangleF rect = new RectangleF ( 0, 0, 1000, 1000 );
    CharacterRange[] ranges = { new CharacterRange ( 0, text.Length ) };
    Region[] regions = new Region[1];

    format.SetMeasurableCharacterRanges ( ranges );
    format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;

    regions = graphics.MeasureCharacterRanges ( text, font, rect, format );
    rect = regions[0].GetBounds ( graphics );

    return (int)( rect.Right );
}

归功于problem with TextRenderer.MeasureText

除此之外,还尝试使用带有长字符串的stringbuilder,然后将字符串拆分成更小的字符串并测量它们并将它们加在一起

答案 1 :(得分:0)

给出了类似的例子Here。他们还解决了maxLength问题 msdn

重要提示:了解文章中如何使用MaxLength。

private static void DrawALineOfText(PaintEventArgs e)
{
    // Declare strings to render on the form. 
    string[] stringsToPaint = { "Tail", "Spin", " Toys" };

    // Declare fonts for rendering the strings.
    Font[] fonts = { new Font("Arial", 14, FontStyle.Regular), 
        new Font("Arial", 14, FontStyle.Italic), 
        new Font("Arial", 14, FontStyle.Regular) };

    Point startPoint = new Point(10, 10);

    // Set TextFormatFlags to no padding so strings are drawn together.
    TextFormatFlags flags = TextFormatFlags.NoPadding;

    // Declare a proposed size with dimensions set to the maximum integer value.
    Size proposedSize = new Size(int.MaxValue, int.MaxValue);

    // Measure each string with its font and NoPadding value and  
    // draw it to the form. 
    for (int i = 0; i < stringsToPaint.Length; i++)
    {
        Size size = TextRenderer.MeasureText(e.Graphics, stringsToPaint[i], 
            fonts[i], proposedSize, flags);
        Rectangle rect = new Rectangle(startPoint, size);
        TextRenderer.DrawText(e.Graphics, stringsToPaint[i], fonts[i],
            startPoint, Color.Black, flags);
        startPoint.X += size.Width;
    }

}

Source