Adding a Vertex to a closed Polyline in AutoCAD

3.9k Views Asked by At

I am trying to insert a new vertex to an existing closed polyline through AutoCAD .Net API.

I have a method for inserting a vertex to a polyline. But this does not work for closed polylines for the case shown below. The code fails if the point is on the last edge of the polyline. Can someone see what the issue is?

 public void AddVertexOnPolyline(Point3d addPoint,Polyline editPolyline)
  {
      Document acDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
      Editor pEditor = acDoc.Editor;
      int chk = 1;
      try
      {
          for (int i = 0; (i <= (editPolyline.NumberOfVertices - 1)); i++)
          {
              double dist1 = editPolyline.GetDistAtPoint(addPoint);
              double dist2 = editPolyline.GetDistAtPoint(editPolyline.GetPoint3dAt(i));

              if ((editPolyline.GetDistAtPoint(addPoint) < (editPolyline.GetDistAtPoint(editPolyline.GetPoint3dAt(i)))) && chk != 0)
              {
                  Point2d pnt2 = new Point2d(addPoint.X, addPoint.Y);
                  editPolyline.AddVertexAt(i, pnt2, 0, 0, 0);
                  chk = 0;
                  break;
              }
          }
      }
      catch (System.Exception ex)
      {
          throw;
      }
  }

Note: I also posted it on autodesk discussion forums

1

There are 1 best solutions below

1
On

To add a vertex to a polylineclosed or not, use the method AddVertexAt. This code can replace your method:

Point2d addPoint = new Point2d(50.0, 50.0);
polyline.AddVertexAt(3, addPoint, 0, 0, 0);

Your method is not doing that at all. You're using the method GetDistAtPoint which calculate the distance between the start of the polyline and the point given as parameter. If the point isn't on the polyline, the method will throw an exception.

The method checks if there is a vertex which has a greater distance than the distance of the given point.