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:

when MaxTextWidth is set to 300:

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

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 Backgroundproperty toTransparent
- 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));
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论