Add some text in a WPF shape
I have a custom WPF control MyLine that should represent or not some text in its middle.
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;
}
}
}
So, how should I add the text here?
Create a FormattedText object and then create a Geometry from it:
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);
精彩评论