Add WPF Text

I have a WPF MyLine user control that should or may not contain any text in the 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 do I add text here?

+3
source share
1 answer

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);
+6
source

Source: https://habr.com/ru/post/1774855/


All Articles