添加实体通用函数
public static ObjectId AddToModelSpace(this Database db, Entity ent)
{
ObjectId endId;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
BlockTable bt = (BlockTable)trans.GetObject(
db.BlockTableId, OpenMode.ForRead);
BlockTableRecord btr = (BlockTableRecord)trans.GetObject(
bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
endId = btr.AppendEntity(ent);
trans.AddNewlyCreatedDBObject(ent, true);
trans.Commit();
}
return endId;
}
public static List<ObjectId> AddToModelSpace(this Database db, params Entity[] ents)
{
List<ObjectId> res = new List<ObjectId>();
foreach(Entity entity in ents){
res.Add(AddToModelSpace(db, entity));
}
return res;
}
IExtensionApplication 接口
public class xx: IExtensionApplication { public void Initialize() { Document doc = Application.DocumentManager.MdiActiveDocument; // 向文档发送缩放命令 doc.SendStringToExecute("_ZOOM A ", true, false, true); } public void Terminate() { // 此方法在关闭autocad时才会调用,故无法使用ed对象在cad显示终止信息。 System.Diagnostics.Debug.WriteLine("程序结束,可做清理工作"); } }
Initialize 方法在加载插件时被调用,通过 doc.SendStringToExecute 发送 _ZOOM A 命令给 AutoCAD。它会将当前视图缩放以适应所有对象的大小,确保它们在当前视口中完全可见。
SendStringToExecute 函数
doc.SendStringToExecute("_ZOOM A ", true, false, true);
-
第一个参数是要发送的字符串命令。
-
第二个参数是指示命令是否立即执行的布尔值。如果设置为
true
,则命令会立即执行;如果设置为false
,则命令会等待当前命令执行完成后再执行。通常情况下,我们希望命令立即执行,所以会将其设置为true
。 -
第三个参数是指示是否在命令执行后清除命令历史记录的布尔值。如果设置为
true
,则命令历史记录将被清除;如果设置为false
,则命令历史记录将保留。通常情况下,我们希望保留命令历史记录,所以会将其设置为false
。 -
第四个参数是指示是否显示命令提示的布尔值。如果设置为
true
,则会显示命令提示;如果设置为false
,则不会显示命令提示。通常情况下,我们希望显示命令提示,所以会将其设置为true
。
这里需要注意一下第三个参数,当你将第三个参数设置为true
时,即使命令成功执行完成,但后续的命令也无法被正确识别和执行,因为它们已经被从命令历史记录中清除了。
P/Invoke 技术
由于书中开发环境与我的不同,故一些使用的c++函数无法使用,会出现一下这种异常:
System.EntryPointNotFoundException HResult=0x80131523 Message=无法在 DLL“acad.exe”中找到名为“?acedHatchPalletteDialog@@YA_NPB_W_NAAPA_W@Z”的入口点。
为解决此问题需查看autocad中封装的c++函数名,在此可使用vs2018自带的dumpbin.exe程序,位置如下:
xx\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.37.32822\bin\Hostx64\x64
然后可通过cmd命令行执行指令。首先示例代码所使用的dll,例如
[SuppressUnmanagedCodeSecurity] [DllImport("acad.exe", EntryPoint = "?acedHatchPalletteDialog@@YA_NPEB_W_NAEAPEA_W@Z", CharSet = CharSet.Auto)] static extern bool acedHatchPalletteDialog(string currentPattern, bool showCustom, out IntPtr newPattern);
可知使用的是acad.exe中的函数,那么可执行一下命令:
xx\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.37.32822\bin\Hostx64\x64>dumpbin.exe /Exports "D:\app\autocad\AutoCAD 2018\acad.exe" /Out:"D:\acadexe.txt"
-- Microsoft (R) COFF/PE Dumper Version 14.37.32825.0
-- Copyright (C) Microsoft Corporation. All rights reserved.
接着去查看生成的txt找到正确的函数名替换。
相关图形绘制代码
直线:
[CommandMethod("FirstLine")]
public static void FirstLine()
{
Database db = HostApplicationServices.WorkingDatabase;
Autodesk.AutoCAD.Geometry.Point3d startPoint = new Autodesk.AutoCAD.Geometry.Point3d(0, TempValue, 0);
Autodesk.AutoCAD.Geometry.Point3d endPoint = new Autodesk.AutoCAD.Geometry.Point3d(TempValue, TempValue, 0);
Line line = new Line(startPoint, endPoint);
db.AddToModelSpace(line); //扩展方法
}
[CommandMethod("SecondLine")]
public static void SecondLine()
{
Database db = HostApplicationServices.WorkingDatabase;
Autodesk.AutoCAD.Geometry.Point3d startPoint = new Autodesk.AutoCAD.Geometry.Point3d(0, TempValue, 0);
Autodesk.AutoCAD.Geometry.Point3d endPoint = new Autodesk.AutoCAD.Geometry.Point3d(0, TempValue * 2, 0);
Line line = new Line(startPoint, endPoint);
db.AddToModelSpace(line); //扩展方法
}
// 移动
[CommandMethod("EditLine")]
public static void EditLine()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
// 事务处理管理器
Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;
using (Transaction tr1 = tm.StartTransaction())
{
Autodesk.AutoCAD.Geometry.Point3d ptStart = Autodesk.AutoCAD.Geometry.Point3d.Origin;
Autodesk.AutoCAD.Geometry.Point3d ptEnd = new Autodesk.AutoCAD.Geometry.Point3d(TempValue, 0, 0);
Line line1 = new Line(ptStart, ptEnd);
ObjectId id1 = db.AddToModelSpace(line1);
// 事务2
using(Transaction tr2 = tm.StartTransaction())
{
line1.UpgradeOpen(); // zoom
line1.ColorIndex = 5;
ObjectId id2 = id1.Copy(ptStart, ptEnd);
id2.Rotate(ptEnd, System.Math.PI / 2);
// 事务3
using (Transaction tr3 = tm.StartTransaction())
{
Line line2 = (Line)tr3.GetObject(id2, OpenMode.ForWrite);
line2.ColorIndex = 1;
// db.AddToModelSpace(line2);
// tr3.Abort();
}
tr2.Commit();
}
tr1.Commit();
}
}
圆和圆弧:
[CommandMethod("Fan")]
public static void Fan()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 定义圆弧三个点
Autodesk.AutoCAD.Geometry.Point3d startPoint = new Autodesk.AutoCAD.Geometry.Point3d(TempValue, 0, 0);
Autodesk.AutoCAD.Geometry.Point3d pointOnArc = new Autodesk.AutoCAD.Geometry.Point3d(50, 25, 0);
Autodesk.AutoCAD.Geometry.Point3d endPoint = new Autodesk.AutoCAD.Geometry.Point3d();
// 调用三点法画圆弧的扩展函数创建扇形的圆弧
Arc arc = new Arc();
arc.CreateArc(startPoint, pointOnArc, endPoint);
// 创建扇形的两条半径
Line line1 = new Line(arc.Center, startPoint);
Line line2 = new Line(arc.Center, endPoint);
// 一次性添加实体到模型空间,完成扇形的创建
db.AddToModelSpace(line1, line2, arc);
trans.Commit();
}
}
多线段:
[CommandMethod("AddPolyline")]
public static void AddPolyline()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
Point2d startPoint = Point2d.Origin;
Point2d endPoint = new Point2d(TempValue, TempValue);
Point2d pt = new Point2d(60, 70);
Point2d center = new Point2d(50, 50);
// 创建直线
Polyline polyline = new Polyline();
polyline.CreatePolyline(startPoint, endPoint);
// 创建矩形
Polyline rectangle = new Polyline();
rectangle.CreateRectangle(pt, endPoint);
// 创建正六边形
Polyline polygon = new Polyline(); // 要是用 rectangle.CreatePolygon(Point2d.Origin, 6, 30); 会很奇怪
polygon.CreatePolygon(Point2d.Origin, 6, 30);
// 创建半径为30的圆
Polyline circle = new Polyline();
circle.CreatePolyCircle(center, 30);
// 创建圆弧,起点角度为45度,重点角度为225度
Polyline arc = new Polyline();
double startAngle = 45;
double endAngle = 225;
arc.CreatePolyArc(center, 50, startAngle.DegreeToRadian(), endAngle.DegreeToRadian());
// 添加对象到模型空间
db.AddToModelSpace(polyline, rectangle, polygon, circle, arc);
trans.Commit();
}
}
椭圆和样条曲线:
[CommandMethod("AddEllipse")]
public void AddEllipse()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
Vector3d majorAxis = new Vector3d(40, 0, 0); // 长轴端点
// 使用中心点、所在平面、长轴矢量和半径比例(0.5)创建一个椭圆
Ellipse ellipse1 = new Ellipse(Autodesk.AutoCAD.Geometry.Point3d.Origin, Vector3d.ZAxis, majorAxis, 0.5, 0, 2 * Math.PI);
Ellipse ellipse2 = new Ellipse(); //新建一个椭圆
// 定义外接矩阵的两个角点
Autodesk.AutoCAD.Geometry.Point3d pt1 = new Autodesk.AutoCAD.Geometry.Point3d(-40, -40, 0);
Autodesk.AutoCAD.Geometry.Point3d pt2 = new Autodesk.AutoCAD.Geometry.Point3d(40, 40, 0);
// 根据外接矩阵创建椭圆
ellipse2.CreateEllipse(pt1, pt2);
// 创建椭圆弧
majorAxis = new Vector3d(0, 40, 0);
Ellipse ellipseArc = new Ellipse(Autodesk.AutoCAD.Geometry.Point3d.Origin, Vector3d.ZAxis, majorAxis, 0.25, Math.PI, 2 * Math.PI);
// 添加实体到模型空间
db.AddToModelSpace(ellipse1, ellipse2, ellipseArc);
trans.Commit();
}
}
[CommandMethod("AddSpline")]
public void AddSpline()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 使用样本点直接创建4阶样条曲线
Point3dCollection pts = new Point3dCollection();
pts.Add(new Autodesk.AutoCAD.Geometry.Point3d(0, 0, 0));
pts.Add(new Autodesk.AutoCAD.Geometry.Point3d(10, 30, 0));
pts.Add(new Autodesk.AutoCAD.Geometry.Point3d(60, 80, 0));
pts.Add(new Autodesk.AutoCAD.Geometry.Point3d(100, 100, 0));
Spline spline1 = new Spline(pts, 4, 0);
// 根据起点和终点为的切线方向创建样条曲线
Vector3d startTangent = new Vector3d(5, 1, 0);
Vector3d endTangent = new Vector3d(5, 1, 0);
pts[1] = new Autodesk.AutoCAD.Geometry.Point3d(30, 10, 0);
pts[2] = new Autodesk.AutoCAD.Geometry.Point3d(80, 60, 0);
Spline spline2 = new Spline(pts, startTangent, endTangent, 4, 0);
db.AddToModelSpace(spline1, spline2);
trans.Commit();
}
}
文字:
[CommandMethod("AddText")]
public static void AddText()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
DBText textFirst = new DBText(); // 创建第一个单行文字
textFirst.Position = new Autodesk.AutoCAD.Geometry.Point3d(50, 50, 0); // 文字位置
textFirst.Height = 5; // 文字高度
// 设置文字内容,特殊格式 ≈、下画线和平方
textFirst.TextString = "面积" + TextTools.AlmostEqual + TextTools.Underline
+ "2000" + TextTools.Underline + "m" + TextTools.Square;
// 设置文字的水平对齐方式为居中
textFirst.HorizontalMode = TextHorizontalMode.TextCenter;
// 设置文字的垂直对齐方式为居中
textFirst.VerticalMode = TextVerticalMode.TextVerticalMid;
// 设置文字的对齐点
textFirst.AlignmentPoint = textFirst.Position;
DBText textSecond = new DBText(); // 创建第二个单行文字
textSecond.Height = 5; // 文字高度
// 设置文字内容,特殊格式 角度、希腊字母和度数
textSecond.TextString = TextTools.Angle + TextTools.Belta + "=45" + TextTools.Degree;
// 设置文字的水平对齐方式为居中
textSecond.HorizontalMode = TextHorizontalMode.TextCenter;
// 设置文字的垂直对齐方式为居中
textSecond.VerticalMode = TextVerticalMode.TextVerticalMid;
// 设置文字的对齐点
textSecond.AlignmentPoint = new Autodesk.AutoCAD.Geometry.Point3d(50, 40, 0);
DBText textLast = new DBText();
textLast.Height = 5; // 文字高度
// 设置文字内容,特殊格式 直径和公差
textLast.TextString = TextTools.Diameter + "30的直径偏差为" + TextTools.Tolerance + "0.01";
// 设置文字的水平对齐方式为居中
textLast.HorizontalMode = TextHorizontalMode.TextCenter;
// 设置文字的垂直对齐方式为居中
textLast.VerticalMode = TextVerticalMode.TextVerticalMid;
// 设置文字的对齐点
textLast.AlignmentPoint = new Autodesk.AutoCAD.Geometry.Point3d(50, 30, 0);
db.AddToModelSpace(textFirst, textSecond, textLast); // 添加文本到模型空间
trans.Commit();
}
}
[CommandMethod("AddStackTest")]
public static void AddStackTest()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
MText mtext = new MText(); // 创建多行文字对象
mtext.Location = new Autodesk.AutoCAD.Geometry.Point3d(100, 20, 0); // 位置
// 创建水平分数形式的堆叠文字
string firstLine = TextTools.StackText(TextTools.Diameter + "20",
"H7", "P7", StackType.HorizontalFracture, 0.5);
// 创建斜分数形式的堆叠文字
string secondLine = TextTools.StackText(TextTools.Diameter + "20",
"H7", "P7", StackType.ItalicFracture, 0.5);
// 创建公差形式的堆叠文字
string lastLine = TextTools.StackText(TextTools.Diameter + "20",
"+0.020", "-0.010", StackType.Tolerance, 0.5);
mtext.Contents = firstLine + MText.ParagraphBreak + secondLine + "\n" + lastLine;
mtext.TextHeight = 5; // 文本高度
mtext.Width = 0; // 文本宽度,设为0表示不会自动换行
// 设置多行文字为正中对齐
mtext.Attachment = AttachmentPoint.MiddleCenter;
db.AddToModelSpace(mtext); // 添加文本到模型空间
trans.Commit();
}
}
填充:
[CommandMethod("AddHatch")]
public static void AddHatch()
{
Database db = HostApplicationServices.WorkingDatabase;
// 创建一个正六边形
Polyline polygon = new Polyline();
polygon.CreatePolygon(new Point2d(500, 200), 6, 30);
// 创建一个圆
Circle circle = new Circle();
circle.Center = new Autodesk.AutoCAD.Geometry.Point3d(500, 200, 0);
circle.Radius = 10;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 创建一个圆
ObjectId polygonId = db.AddToModelSpace(polygon);
ObjectId circleId = db.AddToModelSpace(circle);
// 创建一个ObjectId集合类对象,用于存储填充边界的ObjectId
ObjectIdCollection ids = new ObjectIdCollection();
ids.Add(polygonId); // 将正六边形的ObjectId添加到边界集合中
Hatch hatch = new Hatch(); // 创建填充对象
hatch.PatternScale = 0.5; // 设置填充图案的比例
// 创建填充图案选项板
HatchPalletteDialog dlg = new HatchPalletteDialog();
// 显示填充图案选项板
bool isOk = dlg.ShowDialog();
// 如果用户选择了填充图案,则设置填充图案名为所选的图案名,否则为当前图案名
string patterName = isOk ? dlg.GetPattern() : HatchTools.CurrentPattern;
// 根据填充图案名创建填充,类型为预定义与边界关联
hatch.CreateHatch(HatchPatternType.PreDefined, patterName, true);
// 为填充添加外边界(正六边形)
hatch.AppendLoop(HatchLoopTypes.Outermost, ids);
ids.Clear();
ids.Add(circleId); // 将圆的ObjectId 添加到边界集合中
// 为填充添加内边界(圆)
hatch.AppendLoop(HatchLoopTypes.Default, ids);
hatch.EvaluateHatch(true);
//db.AddToModelSpace(textFirst, textSecond, textLast); // 添加文本到模型空间
trans.Commit();
}
}
[CommandMethod("AddGradientHatch")]
public static void AddGradientHatch()
{
Database db = HostApplicationServices.WorkingDatabase;
// 创建一个三角形
Polyline triangle = new Polyline();
triangle.CreatePolygon(new Point2d(550, 200), 3, 30);
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 将三角形添加到模型空间中
ObjectId triangleId = db.AddToModelSpace(triangle);
// 创建一个ObjectId集合类对象,用于存储填充边界的ObjectId
ObjectIdCollection ids = new ObjectIdCollection();
ids.Add(triangleId); // 将三角形的ObjectId添加到边界集合中
Hatch hatch = new Hatch(); // 创建填充对象
// 创建两个Color类变量,分别为填充的起始颜色(红)和结束颜色(蓝)
Color color1 = Color.FromColorIndex(ColorMethod.ByLayer, 1);
Color color2 = Color.FromRgb(0, 0, 255);
// 创建渐变填充,与边界无关联
hatch.CreateGradientHatch(HatchGradientName.Cylinder, color1, color2, false);
// 为填充添加外边界(三角形)
hatch.AppendLoop(HatchLoopTypes.Default, ids);
// 计算并显示填充对象
hatch.EvaluateHatch(true);
trans.Commit();
}
}
面域:
[CommandMethod("AddRegion")]
public void AddRegion()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 创建一个三角形
Polyline triangle = new Polyline();
triangle.CreatePolygon(new Point2d(550, 200), 3, 30);
// 根据三角形创建面域
List<Region> regions = RegionTools.CreateRegion(triangle);
if (regions.Count == 0) return; // 创建失败的情况
ObjectId regionId = db.AddToModelSpace(regions[0]); //将面域添加到数据库
Region region = regions[0];
getAreaProp(region); // 获取面域的质量特征
// 新值一下渐变
ObjectIdCollection ids = new ObjectIdCollection();
ids.Add(regionId); // 将三角形的ObjectId添加到边界集合中
Hatch hatch = new Hatch(); // 创建填充对象
hatch.PatternScale = 0.5; // 设置填充图案的比例
// 创建填充图案选项板
HatchPalletteDialog dlg = new HatchPalletteDialog();
// 显示填充图案选项板
bool isOk = dlg.ShowDialog();
// 如果用户选择了填充图案,则设置填充图案名为所选的图案名,否则为当前图案名
string patterName = isOk ? dlg.GetPattern() : HatchTools.CurrentPattern;
// 根据填充图案名创建填充,类型为预定义与边界关联
hatch.CreateHatch(HatchPatternType.PreDefined, patterName, true);
// 为填充添加外边界(三角形)
hatch.AppendLoop(HatchLoopTypes.Outermost, ids);
hatch.EvaluateHatch(true);
trans.Commit();
}
}
[CommandMethod("AddComplexRegion")]
public void AddComplexRegion()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 创建一个正六边形
Polyline polygon = new Polyline();
polygon.CreatePolygon(new Point2d(500, 200), 6, 30);
// 创建一个圆
Circle circle = new Circle();
circle.Center = new Autodesk.AutoCAD.Geometry.Point3d(500, 200, 0);
circle.Radius = 10;
// 根据正六边形和圆创建面域
List<Region> regions = RegionTools.CreateRegion(polygon, circle);
if (regions.Count == 0) return; // 创建失败的情况
// 使用LINQ按面积对面域进行排序
List<Region> orderRegions = (from r in regions orderby r.Area select r).ToList();
// 对面域进行布尔操作,获取正六边形减去圆后的部分
orderRegions[1].BooleanOperation(BooleanOperationType.BoolSubtract, orderRegions[0]);
ObjectId regionsId = db.AddToModelSpace(regions[1]); //将面域添加到数据库
Region region = regions[1];
getAreaProp(region); // 获取面域的质量特征
/*
// 新值一下渐变
ObjectIdCollection ids = new ObjectIdCollection();
ids.Add(regionsId); // 将正六边形的ObjectId添加到边界集合中
Hatch hatch = new Hatch(); // 创建填充对象
hatch.PatternScale = 0.5; // 设置填充图案的比例
// 创建填充图案选项板
HatchPalletteDialog dlg = new HatchPalletteDialog();
// 显示填充图案选项板
bool isOk = dlg.ShowDialog();
// 如果用户选择了填充图案,则设置填充图案名为所选的图案名,否则为当前图案名
string patterName = isOk ? dlg.GetPattern() : HatchTools.CurrentPattern;
// 根据填充图案名创建填充,类型为预定义与边界关联
hatch.CreateHatch(HatchPatternType.PreDefined, patterName, true);
// 为填充添加外边界(正六边形)
hatch.AppendLoop(HatchLoopTypes.Outermost, ids);
hatch.EvaluateHatch(true);
*/
trans.Commit();
}
}
private void getAreaProp(Region region)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\n ---------------- 面域 ----------------");
ed.WriteMessage("\n面积:{0} ", region.Area);
ed.WriteMessage("\n周长:{0} ", region.Perimeter);
ed.WriteMessage("\n边界框上限:{0} ", region.GetExtentsHigh());
ed.WriteMessage("\n边界框下限:{0} ", region.GetExtentsLow());
ed.WriteMessage("\n质心: {0} ", region.GetCentroid());
ed.WriteMessage("\n惯性矩为: {0}; {1} ", region.GetMomInertia()[0], region.GetMomInertia()[1]);
ed.WriteMessage("\n惯性积为: {0} ", region.GetProdInertia());
ed.WriteMessage("\n主力矩为: {0}; {1} ", region.GetPrinMoments()[0], region.GetPrinMoments()[1]);
ed.WriteMessage("\n主方向为: {0}; {1} ", region.GetPrinAxes()[0], region.GetPrinAxes()[1]);
ed.WriteMessage("\n旋转半径为: {0}; {1} ", region.GetRadiiGyration()[0], region.GetRadiiGyration()[1]);
}
尺寸标注:
[CommandMethod("DimTest")]
public void DimTest()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 创建要标注的图像
Line line1 = new Line(new Autodesk.AutoCAD.Geometry.Point3d(30, 20, 0), new Autodesk.AutoCAD.Geometry.Point3d(120, 20, 0));
Line line2 = new Line(new Autodesk.AutoCAD.Geometry.Point3d(120, 20, 0), new Autodesk.AutoCAD.Geometry.Point3d(120, 40, 0));
Line line3 = new Line(new Autodesk.AutoCAD.Geometry.Point3d(120, 40, 0), new Autodesk.AutoCAD.Geometry.Point3d(90, 80, 0));
Line line4 = new Line(new Autodesk.AutoCAD.Geometry.Point3d(90, 80, 0), new Autodesk.AutoCAD.Geometry.Point3d(30, 80, 0));
Arc arc = new Arc(new Autodesk.AutoCAD.Geometry.Point3d(30, 50, 0), 30, Math.PI / 2, Math.PI * 3 / 2);
Circle cir1 = new Circle(new Autodesk.AutoCAD.Geometry.Point3d(30, 50, 0), Vector3d.ZAxis, 15);
Circle cir2 = new Circle(new Autodesk.AutoCAD.Geometry.Point3d(70, 50, 0), Vector3d.ZAxis, 10);
// 将图像添加到模型空间中
db.AddToModelSpace(line1, line2, line3, line4, arc, cir1, cir2);
// 创建一个列表,用于存储标注对象
List<Dimension> dims = new List<Dimension>();
// 创建转角标注(水平)
RotatedDimension dimRotated1 = new RotatedDimension();
// 指定第一条尺寸界线的附着位置
dimRotated1.XLine1Point = line1.StartPoint;
// 指定第二条尺寸界线的附着位置
dimRotated1.XLine2Point = line1.EndPoint;
// 指定尺寸线的位置
dimRotated1.DimLinePoint = GeTools.MidPoint(
line1.StartPoint, line1.EndPoint).PolarPoint(-Math.PI / 2, 10);
dimRotated1.DimensionText = "<>mm"; // 设置标注的文字为标注值+后缀mm
dims.Add(dimRotated1); // 将水平转角标注添加到列表中
// 创建转角标注(垂直)
RotatedDimension dimRotated2 = new RotatedDimension();
dimRotated2.Rotation = Math.PI / 2;
// 指定第一条尺寸界线的附着位置
dimRotated2.XLine1Point = line2.StartPoint;
// 指定第二条尺寸界线的附着位置
dimRotated2.XLine2Point = line2.EndPoint;
// 指定尺寸线的位置
dimRotated2.DimLinePoint = GeTools.MidPoint(
line2.StartPoint, line2.EndPoint).PolarPoint(0, 10);
dims.Add(dimRotated2); // 将垂直转角标注添加到列表中
// 创建转角标注(尺寸公差标注)
RotatedDimension dimRotated3 = new RotatedDimension();
// 指定第一条尺寸界线的附着位置
dimRotated3.XLine1Point = line4.StartPoint;
// 指定第二条尺寸界线的附着位置
dimRotated3.XLine2Point = line4.EndPoint;
// 指定尺寸线的位置
dimRotated3.DimLinePoint = GeTools.MidPoint(
line4.StartPoint, line4.EndPoint).PolarPoint(Math.PI / 2, 10);
// 设置标注的文字为标注值+堆叠文字(公差效果)
dimRotated3.DimensionText = TextTools.StackText("<>", "+0.026", "-0.025", StackType.Tolerance, 0.7);
dims.Add(dimRotated3); // 将垂直转角标注添加到列表中
// 创建对齐标注
AlignedDimension dimAligned = new AlignedDimension();
dimAligned.XLine1Point = line3.StartPoint;
dimAligned.XLine2Point = line3.EndPoint;
dimAligned.DimLinePoint = GeTools.MidPoint(
line3.StartPoint, line3.EndPoint).PolarPoint(Math.PI / 2, 10);
dimAligned.DimensionText = "<>" + TextTools.Tolerance + "0.2";
dims.Add(dimAligned); // 将对齐标注添加到列表中
// 创建半径标注
RadialDimension dimRadial = new RadialDimension();
dimRadial.Center = cir1.Center;
// 用于附着引线的圆或圆弧上的点
dimRadial.ChordPoint = cir1.Center.PolarPoint(GeTools.DegreeToRadian(30), 15);
dimRadial.LeaderLength = 10; // 引线长度
dims.Add(dimRadial);
// 创建直径标注
DiametricDimension dimDiametric = new DiametricDimension();
// 圆或圆弧上第一个直径点的坐标
dimDiametric.ChordPoint = cir2.Center.PolarPoint(GeTools.DegreeToRadian(45), 10);
// 圆或圆弧上第二个直径点的坐标
dimDiametric.FarChordPoint = cir2.Center.PolarPoint(GeTools.DegreeToRadian(-135), 10);
dimDiametric.LeaderLength = 0;
dims.Add(dimDiametric);
// 创建角度标注
Point3AngularDimension dimLineAngular = new Point3AngularDimension();
// 圆或圆弧的圆心、或两尺寸界线间的共有顶点的坐标
dimLineAngular.CenterPoint = line2.StartPoint;
// 指定两条尺寸界线的附着位置
dimLineAngular.XLine1Point = line1.StartPoint;
dimLineAngular.XLine2Point = line2.EndPoint;
// 设置角度标志圆弧上的点
dimLineAngular.ArcPoint = line2.StartPoint.PolarPoint(GeTools.DegreeToRadian(135), 10);
dims.Add(dimLineAngular);
// 创建弧长标注,标注文字取默认值
ArcDimension dimArc = new ArcDimension(arc.Center, arc.StartPoint, arc.EndPoint, arc.Center.PolarPoint(Math.PI, arc.Radius + 10), "<>", db.Dimstyle);
dims.Add(dimArc);
// 创建坐标标注 x
OrdinateDimension dimX = new OrdinateDimension();
dimX.UsingXAxis = true; // 显示X轴值
dimX.DefiningPoint = cir2.Center;
// 指定引线终点,即标注文字显示的位置
dimX.LeaderEndPoint = cir2.Center.PolarPoint(-Math.PI / 2, 20);
dims.Add(dimX);
// 创建坐标标注 y
OrdinateDimension dimY = new OrdinateDimension();
dimY.UsingXAxis = false; // 显示X轴值
dimY.DefiningPoint = cir2.Center;
// 指定引线终点,即标注文字显示的位置
dimY.LeaderEndPoint = cir2.Center.PolarPoint(0, 20);
dims.Add(dimY);
foreach (Dimension dim in dims)
{
dim.DimensionStyle = db.Dimstyle; // 设置标注样式为当前样式
db.AddToModelSpace(dim);
}
trans.Commit();
}
}
引线与形体公差:
[CommandMethod("AddLeader")]
public void AddLeader()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 创建一个在原点直径为 0.219 的圆
Circle circle = new Circle();
circle.Center = Point3d.Origin;
circle.Diameter = 0.219;
// 创建一个多行文本并设置其内容为 4Xφd±0.005(其中d为圆的直径)
MText txt = new MText();
txt.Contents = "4X" + TextTools.Diameter + circle.Diameter + TextTools.Tolerance + "0.005";
txt.Location = new Point3d(1, 1, 0); // 文本位置
txt.TextHeight = 0.2; // 文本高度
db.AddToModelSpace(circle, txt); // 将圆和文本添加到模型空间中
Leader leader = new Leader(); // 创建一个引线对象
// 将圆上一点及文本位置作为引线的顶点
leader.AppendVertex(circle.Center.PolarPoint(Math.PI / 3, circle.Radius));
leader.AppendVertex(txt.Location);
db.AddToModelSpace(leader); // 将引线添加到模型空间中
leader.Dimgap = 0.1; // 设置引线的文字偏移为0.1
leader.Dimasz = 0.1; // 设置引线的箭头大小为0.1
leader.Annotation = txt.ObjectId; // 设置引线的注释对象为文本
leader.EvaluateLeader(); // 计算引线及其关联注释之间的关系
trans.Commit();
}
}
[CommandMethod("AddMLeader")]
public void AddMLeader()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 创建三个点,分别表示引线的终点和两个头点
Point3d ptEnd = new Point3d(90, 0, 0);
Point3d pt1 = new Point3d(80, 20, 0);
Point3d pt2 = new Point3d(100, 20, 0);
MText mText = new MText(); // 创建多行文本
mText.Contents = "多重引线示例"; // 文本内容
MLeader mLeader = new MLeader();
// 为多重引线添加引线束,引线束由基线和一些单引线构成
int leaderIndex = mLeader.AddLeader();
// 在引线束中添加一单引线
int lineIndex = mLeader.AddLeaderLine(leaderIndex);
mLeader.AddFirstVertex(lineIndex, pt1); // 在单引线中添加引线头点
mLeader.AddLastVertex(lineIndex, ptEnd); // 在单引线中添加引线终点
// 在引线束中再添加一单引线,并只设置引线头点
lineIndex = mLeader.AddLeaderLine(leaderIndex);
mLeader.AddFirstVertex(lineIndex, pt2 );
// 设置多重引线的注释为多行文本
mLeader.ContentType = ContentType.MTextContent;
mLeader.MText = mText;
// 将多重引线添加到模型空间
db.AddToModelSpace( mLeader );
trans.Commit();
}
}
[CommandMethod("AddRoadMLeader")]
public void AddRoadMLeader()
{
Database db = HostApplicationServices.WorkingDatabase;
// 获取符合为点的箭头块的ObjectId
ObjectId arrowId = db.GetArrowObjectId(DimArrowBlock.Dot);
// 如果当前图形中还未加入上述箭头块,则加入并获取其ObjectId
if ( arrowId == ObjectId.Null )
{
DimTools.ArrowBlock = DimArrowBlock.Dot;
arrowId = db.GetArrowObjectId(DimArrowBlock.Dot);
}
// 创建一个点列表,在其中添加4个要标注的点
List<Point3d> pts = new List<Point3d>();
pts.Add(new Point3d(150, 0, 0));
pts.Add(new Point3d(150, 15, 0));
pts.Add(new Point3d(150, 18, 0));
pts.Add(new Point3d(150, 20, 0));
// 各标注点对应的文字
List<String> contents = new List<String> { "道路中心线", "机动车道", "人行道", "绿化带" };
using (Transaction trans = db.TransactionManager.StartTransaction())
{
for (int i = 0; i < pts.Count; i++) // 遍历标注点
{
MText txt = new MText(); // 创建多行文本
txt.Contents = contents[i]; // 文本内容
MLeader mLeader = new MLeader(); // 创建多重引线
// 为多重引线添加引线束,引线束由基线和一些单引线构成
int leaderIndex = mLeader.AddLeader();
// 在引线束中添加一条单引线,并设置引线头点和终点
int lineIndex = mLeader.AddLeaderLine(leaderIndex);
mLeader.AddFirstVertex(lineIndex, pts[i]);
mLeader.AddLastVertex(lineIndex, pts[0].PolarPoint(Math.PI / 2, 20 + (i + 1) * 5));
mLeader.ArrowSymbolId = arrowId; // 设置单引线的箭头块 ObjectId
// 设置多重引线的注释为多行文本
mLeader.ContentType = ContentType.MTextContent;
mLeader.MText = txt;
db.AddToModelSpace(mLeader);
mLeader.ArrowSize = 1; // 多重引线箭头大小
mLeader.DoglegLength = 0; // 多重引线基线长度设为0
// 将基线连接到引线文字的下方并且绘制下画线
mLeader.TextAttachmentType = TextAttachmentType.AttachmentBottomLine;
}
trans.Commit();
}
}
[CommandMethod("AddTolerance")]
public void AddTolerance()
{
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
// 创建一个形体公差特征控制框
FeatureControlFrame frame = new FeatureControlFrame();
// 形体公差的几何特征为位置
string geometricSyn = DimFormatCode.Position;
// 形体公差值为 0.20, 且带直径符合,包含条件为最大实体要求
string torlerance = DimFormatCode.Diameter + "0.20" + DimFormatCode.CircleM;
// 形体公差的第一级基准符号,包含条件为最大实体要求
string firstDatum = "A" + DimFormatCode.CircleM;
// 形体公差的第二级基准符号,包含条件为不考虑特征尺寸
string secondDatum = "B" + DimFormatCode.CircleS;
// 形体公差的第三级基准符号,包含条件为最大实体要求
string thirdDatum = "C" + DimFormatCode.CircleL;
// 设置公差特征控制框内容为形体公差
frame.CreateTolerance(geometricSyn, torlerance, firstDatum, secondDatum, thirdDatum);
frame.Location = new Point3d(1, 0.5, 0); // 控制框的位置
frame.Dimscale = 0.05; // 控制框的大小
db.AddToModelSpace(frame); // 控制框添加到模型空间中
trans.Commit();
}
}
文章评论