2010-09-26 158 views
0

我想了解一些文本是多寬。這是我的代碼:FormattedText.GetMaxTextWidths返回null - 爲什麼?

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

問題是w始終爲空。你知道爲什麼嗎?

+1

我才意識到我的答案告訴爲什麼w始終爲空,但不能幫助你獲得文本的寬度。爲此你可以使用'FormattedText.Width'。對於多行文本,它給出了最長行的長度。如果你想每行的長度,我想你必須單獨設置每個行的「文本」屬性。另外,如果你設置了'MaxTextWidth','Width'將是該約束內的長度。 – 2010-09-26 10:32:08

回答

1

FormattedTextClass不會告訴你最大線寬是多少。它反過來工作;你可以告訴它最大的寬度,它會指出如何顯示文本。

這MSDN文章提供了更多信息:Drawing Formatted Text

以示例代碼和重寫OnRender事件的一個窗口,這裏是一行文字看起來當沒有約束被放置在寬度,如:

alt text

MaxTextWidth被設定爲300:

alt text

並且當SetMaxTextWidths被稱爲傳遞的{ 200, 500, 100 }雙陣列(最後寬度被用於所有剩餘的行當存在比陣列條目更多行):

alt text

在所有的上述實施例,我離開了MaxTextHeight設置爲240

,如果你想在OnRender事件Window的運行從文章的代碼有兩點要注意:

  • 設置窗口的Background 屬性Transparent
  • 添加一行代碼繪製文本後面的白色背景:

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