Hi! The method public void DrawString( string s, Font font, Brush brush, RectangleF layoutRectangle );
enables me to apply a word wrap functionality according to the width of the layoutRectangle. However, I want the hole wrapped string to be visible, that means I need to determine the height of the string in advance so I can set the rectangle height accordingly. How can I figure out the height
Thanks,
kolya

Determine the height of a wrapped string drawn to a control
Sayed Zeeshan
This may be the ticket to my previous question here:
http://forums.microsoft.com/msdn/ShowPost.aspx PostID=18647
Determining number of lines in a TextBox control
For the parameters to MeasureStringExtend,
(1) How do I get a Graphics object representative of the current screen, or can I just use a dummy Graphics object
(2) How do I get the default font in use by .NET for TextBox controls, etc
ryandailey21
http://blog.opennetcf.org/ayakhnin/PermaLink.aspx guid=c43a1365-af59-4d83-81ff-57e0c4a05805
Felipe Garcia
1. Use a stringbuilder instead of performing all those costly string operations.
2. Right now, you are touching each single character, calling the MeasureString method each time. It would increase your performance significantly, if you would
- split the original text into an array of strings (words) with the delimter ' '
- check the width of words rather than characters
- if the width of a set of words exceeds the destination width
- go back to the last word
- if there is not a last word, cut the current word.
However, for my application I need to process quite a lot of text, so I want to make the operation as fast as possible. Hence, I am using a fixed-pitch font where all characters share the same width. Based on this assumption, you can do the following:
//requests a fixed-pitch font
public static SizeF MeasureStringExtend(Graphics g, string text, Font font, int desWidth)
{
SizeF sf = g.MeasureString("X", font);
float singleCharWidth = sf.Width;
float singleCharHeight = sf.Height;
int maxNumCharsLine = (int)(desWidth / singleCharWidth);
int pointer = maxNumCharsLine;
int lineCount = 1;
int indexOfLastChar = text.Length-1;
while(pointer < indexOfLastChar)
{
int posLastWhite = text.LastIndexOf(" ", pointer, maxNumCharsLine);
//space found
if(posLastWhite > -1)
{
pointer = posLastWhite;
}
pointer += maxNumCharsLine;
lineCount++;
}
SizeF sfResult = new SizeF(desWidth, lineCount* sf.Height);
return sfResult;
}
Avia
AlexY's method was definitely the ticket.
However, there is a minor bug in AlexY's method with short strings, so I made an addition near the end of AlexY's routine:
else
{
lines = 1;
}