Measure text height wrapped in a specified width

2019-05-18 17:07发布

问题:

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.

回答1:

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.



回答2:

var size = TextRenderer.MeasureText(FieldValue, InvoiceFont, new Size(105, 16), TextFormatFlags.WordBreak);
RectangleF rectF1 = new RectangleF(xProductName, CurrentY, size.Width, size.Height);
g.DrawString(FieldValue, InvoiceFont, Brushes.Black, rectF1);


标签: c# text graphics