I have a long string (~100k characters). I need to know the length for this string. I call
Size s = TextRenderer.MeasureText(graphics, text, font);
But it returns width equals 7. Only if text length <= 43679 it returns correct value!
Also, if I insert the text in the text box, the text is not visible in the text box! I can select text with mouse, copy via "Ctrl+C", but text not visible. MaxLength property is more than the text length.
I've looked on msdn, but haven't found any information about maximum text length which is used in MeasureText and TextBox.
Where I can find documentation about this? Is there any way to increase maximum text length? Do these values depend on the operating system and computer performance?
Try using this code for measuring strings, textrenderer isnt accurate
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 );
}
credit to problem with TextRenderer.MeasureText
Other then that also try using stringbuilder with long strings and then even split the strings into smaller ones and measure those and add it together
Similar example was given Here . Also they addressed the maxLength issue on
msdn
Important : See how the MaxLength is used in the article.
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