MeasureString problem

J

Jesse Wade

I'm trying to create a function that will pad a string with spaces so
that the resulting string is a specific width (in this case 50points).
As expected, the following code when passed an empty string will add
a space and I see the width increase. All subsequent times through
the loop, the width does not increase though the spaces are being
added to "value"... Please help!

private string AdjustSpace(string text){
Form f = new Form();
Graphics g = f.CreateGraphics();
g.PageUnit = GraphicsUnit.Point;
float width;
SizeF size;
do{
size = g.MeasureString(text, new
Font(System.Drawing.FontFamily.GenericSerif,10));
width = size.Width;
text = " " + text;
}
while(width<50);

return text;
}
 
B

BMermuys

Hi,
[inline]
Jesse Wade said:
I'm trying to create a function that will pad a string with spaces so
that the resulting string is a specific width (in this case 50points).
As expected, the following code when passed an empty string will add

If the text is empty, all spaces are trailing spaces. And MeasureString by
default doesn't count traling spaces. You need to create a StringFormat
object with the MeasureTrailingSpaces as a FormatFlag..
a space and I see the width increase. All subsequent times through
the loop, the width does not increase though the spaces are being
added to "value"... Please help!

private string AdjustSpace(string text)
{
StringFormat sf = StringFormat.GenericDefault;
sf.FormatFlags|=StringFormatFlags.MeasureTrailingSpaces;
Font fnt = new Font(System.Drawing.FontFamily.GenericSerif,10);
StringBuilder sb = new StringBuilder(text);
Form f = new Form();
Graphics g = f.CreateGraphics();
g.PageUnit = GraphicsUnit.Point;

// check if an extra space fits before actually inserting it
while (g.MeasureString( " "+sb.ToString(), fnt, 0, sf ).Width <=
50f)
{
sb.Insert( 0, ' ' );
}

fnt.Dispose();
g.Dispose();
frm.Dispose();
return sb.ToString();
}

Creating a Form each time is a bit of an overhead, maybe you can add a
Graphics parameter.

This will not give you perfect right alignment. If you do the drawing
yourself consider using:

StringFormat sf = StringFormat.GenericDefault;
sf.Alignment = StringAlignment.Far;
g.DrawString( text, myFont, myBrush, new RectangleF( x, y, x+50f, y), sf );


HTH,
Greetings
 

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