Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure wrapped string

I'm trying to create a Control that basically allows me to draw different strings underneath one another. However, the strings' width may not be larger than the control's. In order to solve that problem, I was thinking of passing a RectangleF object to the Graphics.DrawString method. That would wrap strings which are wider than the passed rectangle's width. Although this does solve the problem of not being able to see the whole string if it's too big, there is another problem. If I were to try something like this

Graphics g = e.Graphics; // Paint event
g.DrawString(someText, someFont, someBrush, new PointF(0, 0), someRectangleF);
g.DrawString(someMoreText, someFont, someBrush, new PointF(0, 12), someRectangleF);

the problem would be that if someText gets wrapped, the third line will paint text over of the first text, thus making it hard/impossible to be read.

I was looking for a solution for this problem, and I found some interesting links, which however included the use of a for loop which would measure each character's width and so on. Is there any simpler ways of doing this?

like image 812
haiyyu Avatar asked Feb 02 '12 21:02

haiyyu


People also ask

What is the unit of string?

The length of a string is the number of characters where the width of a control is its size in pixel (per default). You may multiply number of character by a constant number of pixels however. string.

What is the unit of string length?

It turns out that the string length property is the number of code units in the string, and not the number of characters (or more specifically graphemes) as we might expect. For example; "😃" has a length of 2, and "👱‍♂️" has a length of 5!


1 Answers

Can you can use the Graphics.MeasureString method to get the dimensions of the string and draw the next string accordingly?

SizeF size = g.MeasureString(someText, someFont, someRectangleF.Size.Width);
g.DrawString(someText, someFont, someBrush, new PointF(0, 0), someRectangleF);
g.DrawString(someMoreText, someFont, someBrush, new PointF(0, size.Height), someRectangleF);
like image 182
Sam Greenhalgh Avatar answered Oct 03 '22 08:10

Sam Greenhalgh