tags:

views:

14

answers:

1

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?

A: 

The FormattedTextClass doesn'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 OnRender event of a window, here is what a line of text looks like when no constraint is placed on the width:

alt text

when MaxTextWidth is set to 300:

alt text

and when SetMaxTextWidths is 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):

alt text

In all of the above examples, I left the MaxTextHeight set to 240.

A couple of notes if you want to run the code from the article in the OnRender event of a Window:

  • Set the window's Background property to Transparent
  • Add a line of code to draw a white background behind the text:

// Draw a white background
drawingContext.DrawRectangle(Brushes.White, null, new Rect(new Point(0, 0), new Size(this.Width, this.Height)));

// Draw the formatted text string to the DrawingContext of the control.
drawingContext.DrawText(formattedText, new Point(10, 10));
adrift