3

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

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

但它返回宽度等于 7。只有当文本长度 <= 43679 它返回正确的值!

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

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

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

4

2 回答 2

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

归功于TextRenderer.MeasureText 的问题

除此之外,还尝试使用带有长字符串的字符串生成器,然后甚至将字符串拆分为较小的字符串并测量它们并将其加在一起

于 2014-10-08T06:54:44.033 回答
0

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

重要提示:请参阅文章中如何使用 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;
    }

}

资源

于 2014-10-08T07:21:40.940 回答