简体   繁体   中英

To get length of WPF path

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??

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.

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM