Graphics.MeasureString() function issues

R

Rob

I am trying to measure the length of a string in pixels in a control I
designed. The basic premis is if the string is longer than the
control it will truncate the string and append it with "..."

I have gone through several threads on here looking for answers and
haven't been successful.

Everything seems to go fine until I get to this section of code below.
The first time I use the MeasureString function the variable
iCharCount is set to an extremely large number. (17201029) I am not
sure why this is happening, but this is what seems to be causing my
errors because I get an "InvalidArgumentException" thrown on the line
that takes the Substring.

Does anyone know why my internal variables are becoming corrupt after
calls to MeasureString?

Source:

SizeF mySizeF = e.Graphics.MeasureString(this.Text.ToString(),
this.Font);

string MyTempString = "";
int iCharCount = 0;

if ((mySizeF.Width > (float)this.Width))
{
SizeF tmpLength = e.Graphics.MeasureString(
MyTempString + "...", this.Font);

while (tmpLength.Width < (float)this.Width)
{
MyTempString = MyTempString +
this.Text.Substring(iCharCount, 1);
iCharCount ++;
tmpLength = e.Graphics.MeasureString(
MyTempString + "...", this.Font);
}

MyTempString = MyTempString.Substring(0, MyTempString.Length-1);

e.Graphics.DrawString(MyTempString + "...", this.Font,
new SolidBrush(this.ForeColor), myRect);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top