今天我们来学习关于多段线中添加顶点方面知识,这里使用的是autocad2016版,开发环境使用的是visual studio2012,很自然使用的.net4.5,这样做的主要的目的是,在使用polyline时,需要使用到JoinEntities方法,在低版本中,例如AutoCAD2010是没有的,好了,这些都是废话了。这里通过使用选择操作,选择了一条多段线,然后点击多段线上面的点,通过分割曲线函数,将点添加到多段线上。具体操作如gif录制动画所示。
实现的源代码如下图所示。
添加顶点类:
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AddVerticesToPolyline
{
public static class MyExtensions
{
public static Polyline InsertVertices(this Polyline pline, params Point3d[] points)
{
if (points == null || points.Length == 0)
throw new ArgumentException("点不能空、");
var array = points.Select(p => pline.GetParameterAtPoint(pline.GetClosestPointTo(p, false))).ToArray();
Array.Sort(array);
using (var items = pline.GetSplitCurves(new DoubleCollection(array)))
{
if(items.Count < 2)
throw new InvalidOperationException("分割线失败");
var plines = items.Cast<Polyline>();
Polyline result = plines.First();
Polyline[] rest = null;
try
{
rest = plines.Skip(1).ToArray();
result.JoinEntities(rest);
return result;
}
catch (Exception)
{
if(result != null)
result.Dispose();
throw;
}finally{
if (rest != null)
{
foreach (var item in rest)
item.Dispose();
}
}
}
}
}
}
测试操作类:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AddVerticesToPolyline
{
public static class Class1
{
[CommandMethod("ipt")]
public static void InsertVertices()
{
Document doc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
PromptEntityOptions peo = new PromptEntityOptions("\n选择多段线: ");
peo.SetRejectMessage("\nRequires a Polyline,");
peo.AddAllowedClass(typeof(Polyline), false);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK)
return;
var ppo = new PromptPointOptions("\nFirst point to insert vertex at: ");
ppo.AllowNone = true;
List<Point3d> points = new List<Point3d>();
while (true)
{
var ppr = ed.GetPoint(ppo);
if (ppr.Status == PromptStatus.None)
break;
else if (ppr.Status == PromptStatus.Cancel)
return;
points.Add(ppr.Value);
ppo.Message = "\nNext point to insert vertex at: ";
}
if (points.Count == 0)
return;
using (Transaction tr = new OpenCloseTransaction())
{
Polyline pline = (Polyline) tr.GetObject(per.ObjectId, OpenMode.ForRead);
var newPoly = pline.InsertVertices(points.ToArray());
pline.UpgradeOpen();
pline.HandOverTo(newPoly, true, true);
tr.AddNewlyCreatedDBObject(newPoly, true);
tr.AddNewlyCreatedDBObject(pline, false);
tr.Commit();
ed.WriteMessage("\nInserted {0} vertice(s)", points.Count);
}
}
}
}
更多内容,请关注公众号