用C#写一段关于CAD二次开发中多段线偏移的程序,要求线上的点到偏移后的线段离距都是固定的
时间: 2023-06-13 19:05:44 浏览: 108
以下是一个简单的C#程序,用于CAD二次开发中对多段线进行偏移,使得线上的点到偏移后的线段离距固定。该程序使用了CAD的COM接口,需要在程序中引用CAD的类型库。
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
namespace MyCommands
{
public class MyCommandsClass
{
[CommandMethod("MyOffset")]
public void MyOffset()
{
// 获取当前文档和数据库
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
// 提示用户选择多段线
PromptEntityOptions peo = new PromptEntityOptions("请选择多段线:");
peo.SetRejectMessage("请选择一条多段线!");
peo.AddAllowedClass(typeof(Polyline), true);
PromptEntityResult per = doc.Editor.GetEntity(peo);
if (per.Status != PromptStatus.OK) return;
// 打开事务
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 获取多段线对象
Polyline pline = trans.GetObject(per.ObjectId, OpenMode.ForRead) as Polyline;
if (pline == null) return;
// 提示用户输入偏移距离
PromptDoubleOptions pdo = new PromptDoubleOptions("请输入偏移距离:");
pdo.AllowNegative = true;
PromptDoubleResult pdr = doc.Editor.GetDouble(pdo);
if (pdr.Status != PromptStatus.OK) return;
double distance = pdr.Value;
// 计算多段线的偏移路径
Polyline offsetPline = new Polyline();
for (int i = 0; i < pline.NumberOfVertices; i++)
{
Point2d pt = pline.GetPoint2dAt(i);
double bulge = pline.GetBulgeAt(i);
if (i == 0 || i == pline.NumberOfVertices - 1)
{
offsetPline.AddVertexAt(i, pt + new Vector2d(distance, 0), bulge, 0, 0);
}
else
{
Vector2d vec1 = pt - pline.GetPoint2dAt(i - 1);
Vector2d vec2 = pline.GetPoint2dAt(i + 1) - pt;
double angle = vec1.GetAngleTo(vec2) / 2.0;
double offsetDist = distance / Math.Cos(angle);
Vector2d offsetVec = vec1.GetNormal() * offsetDist;
offsetPline.AddVertexAt(i, pt + offsetVec, bulge, 0, 0);
}
}
// 将偏移后的多段线添加到数据库中
BlockTableRecord btr = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
offsetPline.Layer = pline.Layer;
btr.AppendEntity(offsetPline);
trans.AddNewlyCreatedDBObject(offsetPline, true);
// 提交事务
trans.Commit();
}
}
}
}
```
该程序首先提示用户选择一条多段线,然后提示用户输入偏移距离。接着,程序计算多段线的偏移路径,将偏移后的多段线添加到数据库中,并提交事务。注意,在计算偏移路径时,需要考虑多段线的拐弯处,以保证线上的点到偏移后的线段离距固定。