2010-11-15 78 views
3

我有一個自定義的WPF控件MyLine,它應該在中間代表一些文本。在WPF形狀中添加一些文本

public class MyLine : Shape 
{ 
    public double X1, Y1, X2, Y2; 
    public bool IsTextDisplayed; 
    public string Caption; 

    protected override System.Windows.Media.Geometry DefiningGeometry 
    { 
     get 
     { 
      var geometryGroup = new GeometryGroup(); 

      if (IsTextDisplayed) 
      { 
       // calculate text point 
       var midPoint = new Point((X1 + X2)/2.0, (Y1 + Y2)/2.0); 
       // add 'Caption' text in that point 
       // ??? 
      } 

      // Add line 
      geometryGroup.Children.Add(new LineGeometry(
       new Point(X1, Y1), new Point(X2, Y2))); 

      return geometryGroup; 

     } 
    } 
} 

那麼,我應該如何在這裏添加文本?

回答

6

創建FormattedText對象,然後從它創建一個幾何:

FormattedText ft = new FormattedText(
    "Caption", 
    Thread.CurrentThread.CurrentCulture, 
    System.Windows.FlowDirection.LeftToRight, 
    new Typeface("Verdana"), 32, Brushes.Black); 

Geometry geometry = ft.BuildGeometry(midpoint); 

geometryGroup.Children.Add(geometry); 
+1

我唯一的問題是,我的字體畫有相同的「刷」的行...如果線寬2或3的文本是不可讀的... – serhio 2010-11-15 12:26:12

+0

我可以添加一個textBlock或類似的東西嗎? – serhio 2010-11-15 12:34:57

+0

@serhio你有沒有想過一種方法來使用不同的筆刷文本?我正在使用這個問題和批准的答案來解決我遇到的同樣的問題。看起來像Shape和Text在同一個GeometryGroup中是不可能的。 – Corpsekicker 2011-10-31 07:52:29