以WPF形状添加一些文本

时间:2010-11-15 02:22:58

标签: wpf wpf-controls

我有一个自定义WPF控件MyLine,它应该代表或不代表中间的某些文本。

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;

        }
    }
}

那么,我该如何在这里添加文字?

1 个答案:

答案 0 :(得分:6)

创建一个FormattedText对象,然后从中创建一个Geometry:

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