Measure text height wrapped in a specified width

2019-05-18 16:45发布

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.

标签: c# text graphics
2条回答
beautiful°
2楼-- · 2019-05-18 17:23
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);
查看更多
女痞
3楼-- · 2019-05-18 17:33

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.

查看更多
登录 后发表回答