2012-02-24 35 views
2

我想使用FormattedText.BuildGeometry來確定如何佈局字符,以便確定鼠標的邏輯位置。在我的上下文中,FormattedText可以假定爲一行 - 我應該得到一個帶有1個子元素的幾何組,每個子元素都有一個子幾何。除了對於字符「f」和「t」,在FormattedText的文本中重複字符將導致行上的幾何數量比文本中的字符數少一個。FormattedText.BuildGeometry刪除字符

示例代碼:

var tf = new Typeface(new FontFamily("Calibri"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); 
var ft = new FormattedText("ff", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, tf, 14, Brushes.Black); 
var g = ft.BuildGeometry(new Point(0, 0)); 
var gc = (GeometryGroup)((GeometryGroup)g).Children[0]; 
Debug.Assert(gc.Children.Count == ft.Text.Length, "Expected length of " + ft.Text.Length + " but found " + gc.Children.Count); 

你可以只在一個空的WPF應用程序連接這一個按鈕。

對於包含「ff」或「tt」的任何內容都會失敗。更改字體會改變行爲 - 一些字體我沒有找到導致這種情況的字符。

+1

答案如下:http://social.msdn.microsoft.com/Forums/eu/wpf/thread/ddd9c850-25a6-4b99-8a43-5816a0d329a1 – 2012-03-19 12:35:56

回答

1

簡短的回答是,BuildGeometry認爲在glyphs,而不是字符。從documentation(重點煤礦):

返回表示格式化文本,包括所有字形和文字裝飾幾何對象。

在幾種字體中,「ff」和「tt」是ligatures,所以它們由單個字形表示。

請參閱this question瞭解如何做你想做的事情。基本上,BuildHighlightGeometry(Point, int, int)可以返回單個字符的邊界框。您可以迭代邊界框並執行命中測試,直到找到匹配的字符。