4

I have drawn a line using PathGeometry.With the reference from Getting Geometry length I get the length of path using GetFlattenedPathGeometry method, which will convert path to a series of straight lines, and add up the line lengths.The referred code is

public static double GetLength(this Geometry geo)
    {
        PathGeometry path = geo.GetFlattenedPathGeometry();

        double length = 0.0;

        foreach (PathFigure pf in path.Figures)
        {
            Point start = pf.StartPoint;

            foreach (PolyLineSegment seg in pf.Segments)
            {
                foreach (Point point in seg.Points)
                {
                    length += Distance(start, point);
                    start = point;
                }
            }
        }

        return length;
    }

    private static double Distance(Point p1, Point p2)
    {
        return Math.Sqrt(Math.Pow(p1.X - p2.X,2) + Math.Pow(p1.Y - p2.Y,2));
    }

Is there any other better way to get PathGeometry length??

Community
  • 1
  • 1
Swarna Latha
  • 1,004
  • 12
  • 21
  • 1
    Consider a path animation with a custom timeline http://msdn.microsoft.com/en-us/library/aa970561%28v=vs.110%29.aspx Add ticks until the animation reaches the end. `distance = speed x time` translates to `path_length = animation_speed x ticks_required`. – Gusdor Feb 12 '14 at 13:07
  • 1
    Not sure if there is better solution, but definietly you do not need your own Distance function. You can use built in vector support (point-point) returns vector and then you can get length from its properties: `length += (start - point).Length;` – het2cz Feb 12 '14 at 22:22

2 Answers2

1

You can try something like this:

public static double GetLengthOfGeo(Geometry geo)
{
    PathGeometry pg = PathGeometry.CreateFromGeometry(geo);
    Point p; Point tp;
    pg.GetPointAtFractionLength(0.0001, out p, out tp);
    return (pg.Figures[0].StartPoint - p).Length*10000;

}
AlexIsm
  • 11
  • 1
0

With little effort You can convert System.Windows.Media.Geometry to SharpDX.Direct2D1.Geometry that have ComputeLength function:

Calculates the length of the geometry as though each segment were unrolled into a line.

codeDom
  • 1,623
  • 18
  • 54