Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure text height wrapped in a specified width

Tags:

c#

text

graphics

How can I calculate the height needed to render a text wrapped in a specified width?

I found the following method in Graphics

graphicsObj.MeasureString(text, font, width);

But it needs an instance of Graphics and at the time I have not graphics instance. In fact I prefer a static method to find the height. TextRenderer.MeasureText(..) could be an option but it lacks a parameter for proposed width.

like image 913
Ahmad Avatar asked Dec 24 '22 21:12

Ahmad


1 Answers

The overload & flag you need is:

var size = TextRenderer.MeasureText(text, font, new Size(width, height), TextFormatFlags.WordBreak);

For accuracy you should really try to use one of the overloads that accepts a device context.

like image 191
Alex K. Avatar answered Jan 10 '23 10:01

Alex K.