开发者

FormattedText.GetMaxTextWidths returns null - why?

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 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:

FormattedText.GetMaxTextWidths returns null - why?

when MaxTextWidth is set to 300:

FormattedText.GetMaxTextWidths returns null - why?

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):

FormattedText.GetMaxTextWidths returns null - why?

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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜