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?
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.
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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With