AutoCAD2016二次开发&创建Polyline包围面Polygon
今天我们来学习一下高版本的AutoCAD开发,使用的2016版,因此开发的环境需要.net4.5支持,这里使用Visual Studio2012。其实现的功能是利用高版本提供的api接口选择多段线,然后创建一个包围线,这其中涉及到距离偏移的选择。然后使用polygon来创建面,这和其他的地理信息数据中polygon有点类似,但地理信息中的polygon,如在arcgis中是具有拓扑计算能力的,好了,这里说得有点远了。我们来看一下开发的效果。
当然在开发的时候遇到如下的问题。
在代码中加入相应的设置即可,具体实现代码如下。
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DrawPolygonAroundPolyline2
{
public class Class1
{
[CommandMethod("dpap")]
public void demo()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
PromptEntityOptions peo = new PromptEntityOptions("\n选择一条多段线: ");
peo.SetRejectMessage("\n必须为多段线!");
peo.AddAllowedClass(typeof(Polyline), true);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK)
return;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
Polyline pline = (Polyline)tr.GetObject(per.ObjectId, OpenMode.ForRead);
if (pline.Closed)
{
ed.WriteMessage("多段线闭合了.");
return;
}
var pdr = ed.GetDistance("\n指定偏移距离: ");
if (pdr.Status != PromptStatus.OK)
return;
var offsetCurves = pline.GetOffsetCurves(pdr.Value);
if (offsetCurves.Count != 1)
{
ed.WriteMessage("\n曲线创建偏移出现错误");
foreach (DBObject obj in offsetCurves) obj.Dispose();
return;
}
using (var polygon = (Polyline)offsetCurves[0])
{
offsetCurves = pline.GetOffsetCurves(-pdr.Value);
if (offsetCurves.Count != 1)
{
ed.WriteMessage("\n曲线创建偏移出现错误");
foreach (DBObject obj in offsetCurves) obj.Dispose();
return;
}
using (var curve = (Polyline)offsetCurves[0])
using (var line = new Line(polygon.EndPoint, curve.EndPoint))
{
polygon.JoinEntities(new Entity[] { new Line(polygon.EndPoint, curve.EndPoint), curve });
polygon.Closed = true;
var curSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
curSpace.AppendEntity(polygon);
tr.AddNewlyCreatedDBObject(polygon, true);
}
}
tr.Commit();
}
}
}
}
更多内容,请关注公众号