I’m trying to find out how wide some text is. This is my code:
FormattedText ft = new FormattedText("Line 1\r\nLine 2",
System.Globalization.CultureInfo.CurrentCulture,
System.Windows.FlowDirection.LeftToRight,
new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
fontSize,
brush);
double[] w = ft.GetMaxTextWidths();
The problem is that w is always null. Do you know why?
The
FormattedTextClassdoesn’t tell you what the maximum line widths are. It works the other way around; You tell it the maximum widths and it figures out how to display the text.This MSDN article has more information: Drawing Formatted Text
Taking the sample code and overriding the
OnRenderevent of a window, here is what a line of text looks like when no constraint is placed on the width:when
MaxTextWidthis set to 300:and when
SetMaxTextWidthsis called passing in a double array of{ 200, 500, 100 }(the last width is used for all remaining lines when there are more lines than array entries):In all of the above examples, I left the
MaxTextHeightset to 240.A couple of notes if you want to run the code from the article in the
OnRenderevent of aWindow:Backgroundproperty to
Transparent