6

I am writing an addin, which needs to split a polyline into a number of segments taking the number of segments as an input from user. How can I accomplish this?

Divi
  • 255
  • 1
  • 4
  • 16

2 Answers2

8

Use IGeometryBridge2.SplitAtDistances(). Also see the documentation on the equivalent IPolycurve2.SplitAtDistances() and the singular IPolycurve.SplitAtDistance() methods for more explanation.

The IGeometryBridge2 version must be used in .NET.

Edit: This code works for me:

private static IEnumerable<IPolyline> SplitPolylineIntoEqualSegments(IPolyline polyline, int numSegments)
{
    var geombridge = (IGeometryBridge2)new GeometryEnvironmentClass();
    var paths = (IGeometryCollection)polyline;
    for (int i = 0; i < paths.GeometryCount; i++)
    {
        var path = (IPath)paths.get_Geometry(i);
        var distances = new double[Math.Max(1, numSegments - 1)];
        for (int j = 0; j < distances.Length; j++)
        {
            distances[j] = (j + 1.0) / numSegments;
        }
        var polyline2 = PathToPolyline(path);
        geombridge.SplitAtDistances((IPolycurve2)polyline2, ref distances, true, true);
        var splitpaths = (IGeometryCollection)polyline2;
        for (int k = 0; k < splitpaths.GeometryCount; k++)
        {
            var splitpath = (IPath)splitpaths.get_Geometry(k);
            yield return PathToPolyline(splitpath);
        }
    }
}

private static IPolyline PathToPolyline(IPath path)
{
    var polyline = (IPolyline)new PolylineClass();
    var geomcoll = (IGeometryCollection)polyline;
    geomcoll.AddGeometry(path);
    geomcoll.GeometriesChanged();
    return polyline;
}
blah238
  • 35,793
  • 7
  • 94
  • 195
4

This answer is not actually the answer of the actual question. It's the answer of your comment. Because of the code snippet, I wrote it as a answer:

void AddFeatures(List<IPolyline> polylines, IFeatureClass featureClass)
{
    if (featureClass == null)
        return;
    foreach (var polyline in polylines)
    {
        IFeature feature = featureClass.CreateFeature();
        feature.Shape = polyline;

        feature.Store();
    }
    _activeView.Refresh();
}
Emi
  • 2,405
  • 2
  • 22
  • 40
  • :: The code you have given is not giving any errors but it is not giving the correct results.... It is adding the only the first segment not the whole line.... – Avinash Nirankari Feb 19 '13 at 12:56
  • Are you sure about all lines are polylines? because it works for me correctly – Emi Feb 19 '13 at 14:15
  • check these things at debug mode:
    1. count of polylines > 1;
    2. x,y value of the from point and to point of 1st polyline and other polylines are different.
    – Emi Feb 19 '13 at 14:23
  • :: Oh sorry..!! I was doing it the wrong way at first.... It worked... Thanks a Lot for your help..... – Avinash Nirankari Feb 20 '13 at 05:20