سؤال

Why does MeasureString return an incorrect height for a text string when text wrapping to a fixed width?

var labelFont = new Font("Courier New", 11, FontStyle.Bold);
StringFormat format = StringFormat.GenericTypographic;
format.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;    
var size = g.MeasureString("This is a very very very very very very very very very long string", labelFont, 300, format);

size.Height gives an incorrect value. I am finding that I need to take about 1/3 of the height returned in order to get anything like the real height.

I'm trying to draw strings of text onto a background image; so I need to know the height of the wrapped text in order to know the y value of the origin for the next text string.

This code is being used inside an ASP.NET web application.

هل كانت مفيدة؟

المحلول

Your MeasureString call specifies a maximum width of 300 for the string. This means that your very long string is split up into multiple lines, which causes the higher calculated height of the string.

Note that the maximum width of the string is not in characters, but in pixels.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top