Replace characters outside of area with "..."

  • Thread starter Thread starter juvi
  • Start date Start date
J

juvi

Hello,

I am drawing a string on a graphic. How can I replace a part of the string
if it goes outside of the area with "..." (if the text is too long)?

thx

juvi
 
You can use Graphics.MeasureString to determine if your string will be too
large for the available space. You can then chop a segment of the string off
and append "..." and run Graphics.MeasureString again to check if you are
within bounds. While you can estimate how much to trim the string it's not
precise so you may need to repeat until you get a result which looks good in
the available space.

Peter

--
Peter Foot
Microsoft Device Application Development MVP
peterfoot.net | appamundi.com | inthehand.com
APPA Mundi Ltd - Software Solutions for a Mobile World
In The Hand Ltd - .NET Components for Mobility
 
Juvi,

If you'll be doing this a lot, pre-calculate the width of each character;
aka grfx.MeasureString (font, char).Width. Then do something like this
(this is pseudo code, definitely not compilable C#):

int viewableWidth = XYZ; <--- you need to figure this out
viewableWidth -= 3 * ht["."];
String str = "";
while (true)
{
char ch = nextChar;

int charWidth = ht[ch];

if (viewableWidth > widthChar)
{
str += ch;
viewableWidth -= charWidth;
}
else
{
break;
}
}
str += "...";
return str;

To make this more efficient, use a loop instead "for (int i = 0; i < strlen;
i++)" and instead of adding one char per loop, just use substring once at
the end to get all the first chars that will fit.

Hilton
 
Back
Top