Measure wrapped string

余生颓废 提交于 2019-12-22 06:58:07

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/9120555/measure-wrapped-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!