创建和编辑AutoCAD图元(.NET)

可以创建一系列对象,从简单的直线和圆到样条曲线、椭圆和关联填充区域。一般来说,您可以使用 AppendEntity 函数将对象添加到 BlockTableRecord 对象。创建对象后,可以更改其特性,例如图层、颜色和线型。

图形数据库与其他数据库程序类似,可以将模型空间中的Line对象视为表记录,将模型空间视为其数据库表。使用数据库时,必须先打开和关闭记录,然后才能使用它们。存储在 Database 对象中的对象没有什么不同,您可以使用 GetObject 函数从数据库中检索对象并定义如何使用该对象。

本节中的主题

  • 打开和关闭对象(.NET)

  • 创建对象(.NET)

  • 使用选择集(.NET)

    选择集可以由单个对象组成,也可以是更复杂的分组:例如,某个图层上的对象集。

  • 编辑命名对象和2D对象(.NET)

  • 使用图层、颜色和线型(.NET)

  • 保存和恢复图层状态(.NET)

  • 将文本添加到图形(.NET)

打开和关闭对象(.NET)

无论您是在处理对象(如直线、圆和线)还是符号表及其记录,都需要打开对象进行读取或写入。当查询一个对象时,你想打开这个对象进行读取,但是如果你要对这个对象进行修改,你想打开它进行写入。

本节中的主题

  • 使用ObjectIds(.NET)

  • 将事务与事务管理器(.NET)一起使用

  • 不使用事务管理器打开和关闭对象(.NET)

  • 升级和降级Open Objects(.NET)

    通过升级或降级对象,可以将对象的当前打开模式从读更改为写或从写更改为读。

  • 关于使用动态语言(.NET)

    AutoCAD托管.NET API允许您利用.NET 4.0中引入的动态语言编译器(DLR)。

使用ObjectIds(.NET)

数据库中包含的每个对象都被分配了几个唯一的id。访问对象的独特方式包括:

  • Entity handle
  • ObjectId
  • Instance pointer

访问对象的最常见方式是通过其ObjectId。如果您的项目同时使用COM互操作和托管AutoCAD .NET API,则ObjectId非常有效。如果创建自定义AutoLISP函数,则可能需要使用实体句柄。

句柄在AutoCAD会话之间是永久性的,因此,如果需要将图形信息导出到外部文件(稍后可能需要使用该文件来更新图形),则句柄是访问对象的最佳方式。数据库中对象的ObjectId仅在数据库加载到内存中时才存在。一旦数据库关闭,分配给对象的ObjectId就不再存在,并且在下次打开数据库时可能会有所不同。

获取ObjectId

使用对象时,在打开对象进行查询或编辑之前,需要先获取ObjectId。当打开图形文件时,ObjectId将被分配给数据库中的现有对象,而新对象在首次创建时将被分配ObjectId。通常通过以下方式获取数据库中现有对象的ObjectId:

  • 使用 Database 对象的成员属性,例如 Clayer ,它检索当前图层的对象ID
  • 迭代符号表,如图层符号表

打开对象

获取Object Id后,使用 GetObject 函数打开指定Object Id的对象。可以通过以下方式打开对象:

  • Read.打开一个对象进行读取。
  • Write. 如果对象尚未打开,则打开该对象进行写入。
  • Notify.通知。当对象处于关闭状态、打开进行读取或打开进行写入时,打开对象进行通知,但当对象已打开进行通知时,不打开对象进行通知。此模式适用于对象可能从其自身代码中修改自身的情况,例如定义AutoCAD Managed .NET API不支持的自定义对象时。

您应该以最适合访问对象的情况的模式打开对象。由于创建撤消记录,打开对象进行写操作会引入额外的开销。如果不确定要打开的对象是否是要使用的对象,则应将其打开以进行读取,然后将对象从读取模式升级到写入模式。有关升级对象的更多信息,请参阅“升级和降级开放对象(.NET)”。

GetObject 和 Open 函数都返回一个对象。在使用某些编程语言时,您需要根据值被赋给的变量强制转换返回值。如果您使用的是VB.NET,则无需担心转换返回值,因为它已为您完成。

当使用动态编译语言(DLR)时,您不需要担心打开对象进行读取或写入。对象的打开对您来说是透明的,提交对对象所做的更改的过程也是透明的,而不使用事务。

以下示例说明如何获取当前数据库的零层的 LayerTableRecord 。

下面的示例在不再需要事务后手动处置该事务。

1
2
3
4
5
6
7
8
Document acCurDb = Application.DocumentManager.MdiActiveDocument.Database;
Transaction acTrans = acCurDb.TransactionManager.StartTransaction();

LayerTableRecord acLyrTblRec;
acLyrTblRec = acTrans.GetObject(acCurDb.LayerZero,
OpenMode.ForRead) as LayerTableRecord;

acTrans.Dispose();

下面的示例使用 Using 语句在不再需要事务后释放该事务。 Using 语句是首选的编码风格。

1
2
3
4
5
6
7
Document acCurDb = Application.DocumentManager.MdiActiveDocument.Database;
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
LayerTableRecord acLyrTblRec;
acLyrTblRec = acTrans.GetObject(acCurDb.LayerZero,
OpenMode.ForRead) as LayerTableRecord;
}

将事务与事务管理器(.NET)一起使用

事务用于将多个对象上的多个操作组合在一起作为单个操作。事务通过事务管理器启动和管理。一旦一个事务开始,你就可以使用 GetObject 函数打开一个对象。

当您使用使用 GetObject 打开的对象时,事务管理器会跟踪对对象所做的更改。您创建并添加到数据库中的任何新对象都应该使用 AddNewlyCreatedDBObject 函数添加到事务中。对象被编辑或添加到数据库后,您可以保存对数据库所做的更改,并使用使用事务管理器创建的事务对象上的 Commit 函数关闭所有打开的对象。一旦你完成了一个事务,调用 Dispose 函数关闭这个事务。

本节中的主题

  • 使用事务访问和创建对象(.NET)
  • 提交和回滚更改(.NET)
  • 释放对象(.NET)
  • 嵌套事务(.NET)

使用事务访问和创建对象(.NET)

从当前数据库的 TransactionManager 属性访问事务管理器。引用事务管理器后,可以使用以下方法之一来启动或获取事务:

  • StartTransaction-通过创建 Transaction 对象的新实例来启动新事务。当需要多次写入对象并通过使用不同的嵌套级别控制如何回滚更改时,请使用此方法。
  • StartOpenCloseTransation-创建一个 OpenCloseTransaction 对象,它的行为类似于 Transaction 对象,它包装了对象的 Open 和 Close 方法,使其更容易关闭所有打开的对象,而不必显式关闭每个打开的对象。建议在可能被调用未知次数的支持或实用程序函数中使用,并在处理大多数事件处理程序时使用。

一旦有了 Transaction 或 OpenCloseTransaction 对象,就可以使用 GetObject 方法打开存储在数据库中的对象进行读或写。 GetObject 方法返回一个 DBObject ,它可以转换为它所代表的实际对象类型。

在事务处理期间打开的所有打开对象在事务处理结束时关闭。要结束事务,请调用事务对象的 Dispose 方法。如果使用 Using 和 End Using 关键字来指示事务的开始和结束,则不需要调用 Dispose 方法。

在释放事务之前,您应该提交使用 Commit 方法所做的任何更改。如果在处置事务之前没有提交更改,则所做的任何更改都将回滚到事务开始之前的状态。

可以启动多个事务。可以使用 TransactionManager 对象的 NumberOfActiveTransactions 属性检索活动事务的数量,而可以使用 TopTransaction 属性检索最顶部或最新的事务。

事务可以一个嵌套在另一个内部,以便回滚在例程执行期间所做的某些更改。

查询对象

下面的示例演示如何使用事务打开和读取中的对象。使用 GetObject 方法首先打开 BlockTable ,然后打开Model空间记录。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

[CommandMethod("StartTransactionManager")]
public static void StartTransactionManager()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for read
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForRead) as BlockTableRecord;

// Step through the Block table record
foreach (ObjectId asObjId in acBlkTblRec)
{
acDoc.Editor.WriteMessage("\nDXF name: " + asObjId.ObjectClass.DxfName);
acDoc.Editor.WriteMessage("\nObjectID: " + asObjId.ToString());
acDoc.Editor.WriteMessage("\nHandle: " + asObjId.Handle.ToString());
acDoc.Editor.WriteMessage("\n");
}

// Dispose of the transaction
}
}

向数据库添加新对象

下面的示例演示如何在事务中向数据库中添加一个圆对象。使用 GetObject 方法首先打开BlockTable进行读取,然后打开Model空间记录进行写入。打开Model空间进行写操作后,使用 AppendEntity 和 AddNewlyCreatedDBObject 函数将新的Circle对象附加到Model空间以及事务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("AddNewCircleTransaction")]
public static void AddNewCircleTransaction()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartOpenCloseTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle with a radius of 3 at 5,5
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(5, 5, 0);
acCirc.Radius = 3;

// Add the new object to Model space and the transaction
acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);
}

// Commit the changes and dispose of the transaction
acTrans.Commit();
}
}

提交和回滚更改(.NET)

使用事务时,可以决定何时将对对象的更改保存到图形数据库中。您可以使用 Commit 方法保存对事务中打开的对象所做的更改。如果你的程序遇到错误,你可以使用 Abort 方法回滚在事务中所做的任何更改。

如果在调用 Dispose 之前没有调用 Commit ,则回滚事务中所做的所有更改。无论调用 Commit 还是 Abort ,都需要调用 Dispose 来表示事务结束。如果transaction对象是用 Using 语句启动的,则不必调用 Dispose 。

1
2
3
4
5
// Commit the changes made within the transaction
<transaction>.Commit();

// Abort the transaction and rollback to the previous state
<transaction>.Abort();

Dispose 对象(.NET)

在.NET中创建新对象时,必须通过处理过程和垃圾收集从内存中正确释放对象。你可以使用 Dispose 方法或 Using 语句来通知一个对象何时可以进行垃圾回收。在大多数情况下, Using 语句是首选方法,因为它在不再需要对象时进行适当的调用来关闭和释放对象。

您需要在以下条件下释放对象:

  • 总是使用 Transaction 或 DocumentLock 对象
  • 总是使用新创建的数据库对象,从 DBObject 派生的对象,这些对象正在添加到事务中
  • 始终使用新创建的数据库对象,即从 DBObject 派生的对象,这些对象未添加到数据库中
  • 不必与现有的数据库对象,从 DBObject 派生的对象,用transaction对象和 GetObject 方法打开
1
2
3
4
5
6
7
// Dispose an object with the using statement
using (<dataType> <object> = <value>)
// Do something here
}

// Manually dispose of an object with the Dispose method
<object>. Dispose ();

嵌套事务(.NET)

事务可以一个嵌套在另一个内部。您可能有一个外部事务来撤消例程所做的所有更改,而内部事务只撤消所做更改的一部分。当你处理嵌套事务时,你从一个顶层事务开始,它也是最外层的事务。

当您开始新的事务时,它们将被添加到前一个事务中。嵌套事务必须按照与创建它们相反的顺序提交或中止。所以如果你有三个事务,你必须在第二个之前关闭第三个或最里面的一个,最后关闭第一个。如果中止第一个事务,则将撤消所有三个事务所做的更改。

下图显示事务在嵌套时的显示方式。

使用嵌套事务创建和修改对象

下面的示例演示如何使用三个事务创建 Circle 和 Line 对象,然后更改它们的颜色。圆的颜色在第二和第三个事务中改变,但是由于第三个事务被中止,所以只有在第一和第二个事务中所做的改变被保存到数据库中。此外,在创建和关闭活动事务时,会在“命令行”窗口中打印活动事务的数量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;

[CommandMethod("NestedTransactions")]
public static void NestedTransactions()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Create a reference to the Transaction Manager
Autodesk.AutoCAD.DatabaseServices.TransactionManager acTransMgr;
acTransMgr = acCurDb.TransactionManager;

// Create a new transaction
using (Transaction acTrans1 = acTransMgr.StartTransaction())
{
// Print the current number of active transactions
acDoc.Editor.WriteMessage("\nNumber of transactions active: " +
acTransMgr.NumberOfActiveTransactions.ToString());

// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans1.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans1.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle with a radius of 3 at 5,5
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(5, 5, 0);
acCirc.Radius = 3;

// Add the new object to Model space and the transaction
acBlkTblRec.AppendEntity(acCirc);
acTrans1.AddNewlyCreatedDBObject(acCirc, true);

// Create the second transaction
using (Transaction acTrans2 = acTransMgr.StartTransaction())
{
acDoc.Editor.WriteMessage("\nNumber of transactions active: " +
acTransMgr.NumberOfActiveTransactions.ToString());

// Change the circle's color
acCirc.ColorIndex = 5;

// Get the object that was added to Transaction 1 and set it to the color 5
using (Line acLine = new Line(new Point3d(2, 5, 0), new Point3d(10, 7, 0)))
{
acLine.ColorIndex = 3;

// Add the new object to Model space and the transaction
acBlkTblRec.AppendEntity(acLine);
acTrans2.AddNewlyCreatedDBObject(acLine, true);
}

// Create the third transaction
using (Transaction acTrans3 = acTransMgr.StartTransaction())
{
acDoc.Editor.WriteMessage("\nNumber of transactions active: " +
acTransMgr.NumberOfActiveTransactions.ToString());

// Change the circle's color
acCirc.ColorIndex = 3;

// Update the display of the drawing
acDoc.Editor.WriteMessage("\n");
acDoc.Editor.Regen();

// Request to keep or discard the changes in the third transaction
PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");
pKeyOpts.Message = "\nKeep color change ";
pKeyOpts.Keywords.Add("Yes");
pKeyOpts.Keywords.Add("No");
pKeyOpts.Keywords.Default = "No";
pKeyOpts.AllowNone = true;

PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts);

if (pKeyRes.StringResult == "No")
{
// Discard the changes in transaction 3
acTrans3.Abort();
}
else
{
// Save the changes in transaction 3
acTrans3.Commit();
}

// Dispose the transaction
}

acDoc.Editor.WriteMessage("\nNumber of transactions active: " +
acTransMgr.NumberOfActiveTransactions.ToString());

// Keep the changes to transaction 2
acTrans2.Commit();
}
}

acDoc.Editor.WriteMessage("\nNumber of transactions active: " +
acTransMgr.NumberOfActiveTransactions.ToString());

// Keep the changes to transaction 1
acTrans1.Commit();
}
}

不使用事务管理器打开和关闭对象(.NET)

事务使打开和处理多个对象变得更容易,但它们不是打开和编辑对象的唯一方法。除了使用事务之外,您还可以使用 Open 和 Close 方法打开和关闭对象。您仍然需要获得对象ID才能使用 Open 方法。与transactions中使用的 GetObject 方法一样,您需要指定一个开放模式,并且返回值是一个对象。

如果您在使用 Open 方法打开对象后对其进行了更改,则可以使用 Cancel 方法回滚自打开对象以来所做的所有更改。 Cancel 必须在每个要回滚的对象上调用。在关闭对象后,还必须使用 Dispose 方法正确地释放对象,或者可以使用 Using 语句关闭和释放对象。

注意:对象必须与打开和关闭操作配对。如果你使用了没有 Using 语句的 Open 方法,你必须在一个打开的对象上调用 Close 或 Cancel 方法。如果无法关闭对象,将导致读取访问冲突,并导致AutoCAD变得不稳定。

如果您需要处理单个对象,与使用事务管理器相比,使用 Open 和 Close 方法可以减少您可能必须编写的代码行数。但是,建议使用事务来打开和关闭对象。

注意:使用事务时,不应直接使用 Open 和 Close 方法,因为事务管理器可能无法正确打开或关闭对象,这可能会导致AutoCAD变得不稳定。相反,使用 StartOpenCloseTransation 方法创建一个 OpenCloseTransaction 对象,它包装了 Open 和 Close 方法。

查询对象(手动打开和关闭对象)

这个例子演示了如何手动打开和关闭对象,而不使用transaction和 GetObject 方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

[CommandMethod("OpenCloseObjectId")]
public static void OpenCloseObjectId()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Open the Block table for read
BlockTable acBlkTbl = null;

try
{
acBlkTbl = acCurDb.BlockTableId.Open(OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for read
BlockTableRecord acBlkTblRec = null;

try
{
acBlkTblRec = acBlkTbl[BlockTableRecord.ModelSpace].Open(OpenMode.ForRead) as BlockTableRecord;

// Step through the Block table record
foreach (ObjectId acObjId in acBlkTblRec)
{
acDoc.Editor.WriteMessage("\nDXF name: " + acObjId.ObjectClass.DxfName);
acDoc.Editor.WriteMessage("\nObjectID: " + acObjId.ToString());
acDoc.Editor.WriteMessage("\nHandle: " + acObjId.Handle.ToString());
acDoc.Editor.WriteMessage("\n");
}
}
catch (Autodesk.AutoCAD.Runtime.Exception es)
{
System.Windows.Forms.MessageBox.Show(es.Message);
}
finally
{
// Close the Block table
if (!acBlkTblRec.ObjectId.IsNull)
{
// Close the Block table record
acBlkTblRec.Close();
acBlkTblRec.Dispose();
}
}
}
catch (Autodesk.AutoCAD.Runtime.Exception es)
{
System.Windows.Forms.MessageBox.Show(es.Message);
}
finally
{
// Close the Block table
if (!acBlkTbl.ObjectId.IsNull)
{
acBlkTbl.Close();
acBlkTbl.Dispose();
}
}
}

查询对象(使用语句)

下面的示例演示如何使用Using语句打开和关闭对象,而不是手动关闭和释放对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

[CommandMethod("OpenCloseObjectIdWithUsing")]
public static void OpenCloseObjectIdWithUsing()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Open the Block table for read
using (BlockTable acBlkTbl = acCurDb.BlockTableId.Open(OpenMode.ForRead) as BlockTable)
{
// Open the Block table record Model space for read
using (BlockTableRecord acBlkTblRec = acBlkTbl[BlockTableRecord.ModelSpace].Open(OpenMode.ForRead)
as BlockTableRecord)
{
// Step through the Block table record
foreach (ObjectId acObjId in acBlkTblRec)
{
acDoc.Editor.WriteMessage("\nDXF name: " + acObjId.ObjectClass.DxfName);
acDoc.Editor.WriteMessage("\nObjectID: " + acObjId.ToString());
acDoc.Editor.WriteMessage("\nHandle: " + acObjId.Handle.ToString());
acDoc.Editor.WriteMessage("\n");
}

// Close the Block table record
}

// Close the Block table
}
}

向数据库添加新对象

这个例子演示了如何创建一个新的对象,并将其追加到模型空间,而不使用事务管理器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("AddNewCircleOpenClose")]
public static void AddNewCircleOpenClose()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Open the Block table for read
using (BlockTable acBlkTbl = acCurDb.BlockTableId.Open(OpenMode.ForRead) as BlockTable)
{
// Open the Block table record Model space for write
using (BlockTableRecord acBlkTblRec = acBlkTbl[BlockTableRecord.ModelSpace].Open(OpenMode.ForWrite)
as BlockTableRecord)
{
// Create a circle with a radius of 3 at 5,5
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(5, 5, 0);
acCirc.Radius = 3;

// Add the new object to Model space and the transaction
acBlkTblRec.AppendEntity(acCirc);

// Close and dispose the circle object
}

// Close the Block table record
}

// Close the Block table
}
}

升级和降级Open Objects(.NET)

通过升级或降级对象,可以将对象的当前打开模式从读更改为写或从写更改为读。

这些方法可用于升级或降级以前打开的对象:

  • Transaction.GetObject method – 如果对象是用 Transaction.GetObject 方法打开的,则使用该方法以所需的新打开模式重新打开对象。
  • UpgradeOpen and DowngradeOpen methods –如果对象是用 Open 方法或 OpenCloseTransaction.GetObject 打开的,则使用 UpgradeOpen 方法将对象的打开模式从读更改为写,或使用 DowngradeOpen 方法将对象的打开模式从写更改为读。您不需要将对 DowngradeOpen 的调用与每个 UpgradeOpen 配对,因为关闭对象或处置事务将足以清理对象的打开状态。

建议使用与对象的使用方式最匹配的模式打开对象,因为打开对象以读取并查询对象的属性比打开对象以写入并查询对象的属性更有效。如果你不确定一个对象是否需要修改,最好打开对象进行读操作,然后升级它进行写操作,因为这有助于减少程序的开销。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

[CommandMethod("FreezeDoorLayer")]
public static void FreezeDoorLayer()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

// Step through each layer and update those that start with 'Door'
foreach (ObjectId acObjId in acLyrTbl)
{
// Open the Layer table record for read
LayerTableRecord acLyrTblRec;
acLyrTblRec = acTrans.GetObject(acObjId,
OpenMode.ForRead) as LayerTableRecord;

// Check to see if the layer's name starts with 'Door'
if (acLyrTblRec.Name.StartsWith("Door",
StringComparison.OrdinalIgnoreCase) == true)
{
// Check to see if the layer is current, if so then do not freeze it
if (acLyrTblRec.ObjectId != acCurDb.Clayer)
{
// Change from read to write mode
acTrans.GetObject(acObjId, OpenMode.ForWrite);

// Freeze the layer
acLyrTblRec.IsFrozen = true;
}
}
}

// Commit the changes and dispose of the transaction
acTrans.Commit();
}
}

关于使用动态语言(.NET)

AutoCAD托管.NET API允许您利用.NET 4.0中引入的动态语言编译器(DLR)。

使用DLR可以直接访问对象,而无需:

  • 打开一个对象进行读或写,然后在完成后关闭该对象。
  • 利用事务来提交所做的更改。

在使用DLR时,一旦获得对象的ObjectId,就可以直接访问对象的属性和方法。获得ObjectId后,可以将ObjectId赋给数据类型的变量:

  • Object in VB.NET
  • dynamic in C#

获取ObjectId的方式因对象保存到数据库的方式而异。对于存储在表或字典中的对象,您可以通过以下方式访问其ObjectId:

  • 使用ObjectId的Item方法访问集合中的元素。
  • 创建对表或字典的ObjectId的引用,并将其赋值给变量,然后访问数组的元素。

以下示例代码显示了使用DLR访问存储在表或字典中的对象的两个选项:

1
2
3
4
5
6
7
8
9
C#
// Item method
dynamic acCurDb = HostApplicationServices.WorkingDatabase;
dynamic acMSpace = acCurDb.BlockTableId.Item(BlockTableRecord.ModelSpace);

// Reference an element directly from a collection
dynamic acCurDb = HostApplicationServices.WorkingDatabase;
dynamic acBlkTbl = acCurDb.BlockTableId;
dynamic acMSpace = acBlkTbl[BlockTableRecord.ModelSpace];

重要:使用DLR和C#时,您需要引用Microsoft.CSharp库。

使用GetEnumerator方法

在使用DLR的 GetEnumerator 方法时,需要在使用完枚举器对象后显式释放枚举器对象。下面的示例演示了如何在使用完枚举器对象后释放枚举器。

1
2
3
4
5
6
C#
dynamic acCurDb = HostApplicationServices.WorkingDatabase;
var acLtypeTbl = acCurDb.LinetypeTableId;
var acTblEnum = acLtypeTbl.GetEnumerator();
...
acTblEnum.Dispose();

使用LINQ脚本

可以使用LINQ查询来查询带有DLR的图形中的表或字典的内容。下面的示例演示如何使用LINQ查询来查询当前图形中为哪些图层指定了某些状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
[CommandMethod("LINQ")]
public static void LINQExample()
{
dynamic db = HostApplicationServices.WorkingDatabase;
dynamic doc = Application.DocumentManager.MdiActiveDocument;

var layers = db.LayerTableId;
for (int i = 0; i < 2; i++)
{
var newrec = layers.Add(new LayerTableRecord());
newrec.Name = "Layer" + i.ToString();
if (i == 0)
newrec.IsFrozen = true;
if (i == 1)
newrec.IsOff = true;
}

var OffLayers = from l in (IEnumerable<dynamic>)layers
where l.IsOff
select l;

doc.Editor.WriteMessage("\nLayers Turned Off:");

foreach (dynamic rec in OffLayers)
doc.Editor.WriteMessage("\n - " + rec.Name);

var frozenOrOffNames = from l in (IEnumerable<dynamic>)layers
where l.IsFrozen == true || l.IsOff == true
select l;

doc.Editor.WriteMessage("\nLayers Frozen or Turned Off:");

foreach (dynamic rec in frozenOrOffNames)
doc.Editor.WriteMessage("\n - " + rec.Name);
}

示例代码

此页面上的示例代码使用以下名称空间:

1
2
3
4
5
Autodesk.AutoCAD.Runtime
Autodesk.AutoCAD.ApplicationServices
Autodesk.AutoCAD.DatabaseServices
Autodesk.AutoCAD.Colors
Autodesk.AutoCAD.Geometry

下面的示例代码演示了如何将Line添加到当前空间;使用和不使用DLR。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[CommandMethod("ADDLINE")]
public static void AddLine()
{
// Get the current database
Database acCurDb = HostApplicationServices.WorkingDatabase;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a line that starts at 5,5 and ends at 12,3
using (Line acLine = new Line(new Point3d(5, 5, 0),
new Point3d(12, 3, 0)))
{
// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acLine);
acTrans.AddNewlyCreatedDBObject(acLine, true);
}

// Save the new object to the database
acTrans.Commit();
}
}

C#动态语言(DLR)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[CommandMethod("ADDLINE")]
public static void AddLine()
{
// Get the current database
dynamic acCurDb = HostApplicationServices.WorkingDatabase;

// Create a dynamic reference to model or paper space
dynamic acSpace = acCurDb.CurrentSpaceId;

// Create a line that starts at 5,5 and ends at 12,3
dynamic acLine = new Line(new Point3d(5, 5, 0),
new Point3d(12, 3, 0));

// Add the new object to the current space
acSpace.AppendEntity(acLine);
}

下面的示例代码演示了如何将层添加到当前数据库;使用和不使用DLR。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
[CommandMethod("ADDLAYER")]
public static void AddLayer()
{
// Get the current database
Database acCurDb = HostApplicationServices.WorkingDatabase;

using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Returns the layer table for the current database
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

// Check to see if MyLayer exists in the Layer table
if (acLyrTbl.Has("MyLayer") != true)
{
// Open the Layer Table for write
acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite);

// Create a new layer named "MyLayer"
using (LayerTableRecord acLyrTblRec = new LayerTableRecord())
{
acLyrTblRec.Name = "MyLayer";

// Assign the ACI color 3 to the new layer
Color acClr = Color.FromColorIndex(ColorMethod.ByAci, 3);
acLyrTblRec.Color = acClr;

// Add the new layer table record to the layer table and the transaction
acLyrTbl.Add(acLyrTblRec);
acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
}

// Commit the changes
acTrans.Commit();
}

// Dispose of the transaction
}
}

C#动态语言(DLR)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[CommandMethod("ADDLAYER")]
public static void AddLayer()
{
// Get the current database
dynamic acCurDb = HostApplicationServices.WorkingDatabase;

dynamic acLyrTbl = acCurDb.LayerTableId;

// Check to see if MyLayer exists in the Layer table
if (acLyrTbl.Has("MyLayer") != true)
{
// Create a new layer named "MyLayer"
dynamic acLyrTblRec = new LayerTableRecord();
acLyrTblRec.Name = "MyLayer";

// Assign the ACI color 3 to the new layer
dynamic acClr = Color.FromColorIndex(ColorMethod.ByAci, 3);
acLyrTblRec.Color = acClr;

// Add the new layer table record to the layer table
acLyrTbl.Add(acLyrTblRec);
}
}

下面演示了如何逐步遍历并列出当前空间中的所有对象(使用和不使用DLR)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[CommandMethod("LISTOBJECTS")]
public static void ListObjects()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = HostApplicationServices.WorkingDatabase;

using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table record Model space for write
BlockTableRecord acSpace;
acSpace = acTrans.GetObject(acCurDb.CurrentSpaceId,
OpenMode.ForRead) as BlockTableRecord;

// Step through the current space
foreach (ObjectId objId in acSpace)
{
// Display the class and current layer of the object
Entity acEnt = (Entity)acTrans.GetObject(objId, OpenMode.ForRead);
acDoc.Editor.WriteMessage("\nObject Class: " + acEnt.GetRXClass().Name +
"\nCurrent Layer: " + acEnt.Layer +
"\n");
}
acTrans.Commit();
}
}

C#动态语言(DLR)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[CommandMethod("LISTOBJECTS")]
public static void ListObjects()
{
// Get the current document and database
dynamic acDoc = Application.DocumentManager.MdiActiveDocument;
dynamic acCurDb = HostApplicationServices.WorkingDatabase;

// Create a dynamic reference to model or paper space
dynamic acSpace = acCurDb.CurrentSpaceId;

// Step through the current space
foreach (dynamic acEnt in acSpace)
{
// Display the class and current layer of the object
acDoc.Editor.WriteMessage("\nObject Class: " + acEnt.GetRXClass().Name +
"\nCurrent Layer: " + acEnt.Layer +
"\n");
}
}

创建对象(.NET)

AutoCAD通常提供几种不同的方法来创建相同的图形对象。虽然AutoCAD .NET API不提供创建对象的相同组合,但它确实为每种对象类型提供了基本的对象构造函数,而且还为许多对象构造函数提供了替代。

例如,在AutoCAD中,有四种不同的方法可以创建圆:(1)通过指定圆心和半径,(2)通过定义直径的两个点,(3)通过定义圆周的三个点,或(4)通过两条切线和一个半径。但是,在AutoCAD .NET API中,提供了两种创建圆的方法。一种方法不接受任何参数,而第二种方法需要圆心、圆的法线方向和半径。

注意:对象是使用New关键字创建的,然后根据您使用的是容器(符号表或字典)还是 BlockTableRecord 对象,使用 Add 或 AppendEntity 将对象附加到父对象。

设置对象的默认属性值

创建新的图形对象时,将为以下实体属性值分配当前文档的数据库中定义的当前实体值:

  • 颜色
  • 线型
  • 线型比例
  • 线宽
  • 打印样式名称
  • 可见性
  • 透明度

注意:如果对象的属性需要设置为当前数据库的默认值,请调用要更改的对象的 SetDatabaseDefaults 方法。

本节中的主题

  • 确定父对象(.NET)
  • 创建线(.NET)
  • 创建曲线对象(.NET)
  • 创建点对象(.NET)
  • 创建实体填充区域(.NET)
  • 使用面域(.NET)
  • 创建图案填充(.NET)

确定父对象(.NET)

图形对象附加到 BlockTableRecord 对象,如模型或图纸空间。通过 BlockTable 对象参照表示模型和图纸空间的块。如果您想在当前空间而不是特定空间中工作,则可以使用 CurrentSpaceId 属性从当前数据库中获取当前空间的ObjectId。

可以使用 DatabaseServices 命名空间下的 SymbolUtilityServices 类的属性或 GetBlockModelSpaceId 和 GetBlockPaperSpaceId 方法从 BlockTable 对象检索模型和图纸空间的块表记录的ObjectId。

访问模型空间、图纸空间或当前空间

以下示例演示如何访问与模型空间、图纸空间或当前空间关联的块表记录。一旦引用块表记录,就会向块表记录添加一个新线。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;

[CommandMethod("AccessSpace")]
public static void AccessSpace()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record for read
BlockTableRecord acBlkTblRec;

// Request which table record to open
PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");
pKeyOpts.Message = "\nEnter which space to create the line in ";
pKeyOpts.Keywords.Add("Model");
pKeyOpts.Keywords.Add("Paper");
pKeyOpts.Keywords.Add("Current");
pKeyOpts.AllowNone = false;
pKeyOpts.AppendKeywordsToMessage = true;

PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts);

if (pKeyRes.StringResult == "Model")
{
// Get the ObjectID for Model space from the Block table
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;
}
else if (pKeyRes.StringResult == "Paper")
{
// Get the ObjectID for Paper space from the Block table
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.PaperSpace],
OpenMode.ForWrite) as BlockTableRecord;
}
else
{
// Get the ObjectID for the current space from the database
acBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId,
OpenMode.ForWrite) as BlockTableRecord;
}

// Create a line that starts at 2,5 and ends at 10,7
using (Line acLine = new Line(new Point3d(2, 5, 0),
new Point3d(10, 7, 0)))
{
// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acLine);
acTrans.AddNewlyCreatedDBObject(acLine, true);
}

// Save the new line to the database
acTrans.Commit();
}
}

创建线(.NET)

直线是AutoCAD中最基本的对象。您可以创建各种线-单线,以及带有和不带有圆弧的多条线段。通常,通过指定坐标点来绘制直线。创建线时,线将继承图形数据库中的当前设置,例如图层、线型和颜色。

要创建直线,请创建以下对象之一的新实例:

Line
创建一条线。

Polyline
创建二维轻量化对象。

MLine
创建多行。

Polyline2D
创建二维图形。

Polyline3D
创建三维视图。

注意:Polyline 2D对象是AutoCAD 14版之前版本中的旧版图元对象,Polyline对象表示AutoCAD 14版中引入的新优化图元。

本节中的主题

  • 创建直线对象(.NET)
  • 创建多段线对象(.NET)

创建直线对象(.NET)

此示例向模型空间添加一条从(5,5,0)开始到(12,3,0)结束的线。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("AddLine")]
public static void AddLine()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a line that starts at 5,5 and ends at 12,3
using (Line acLine = new Line(new Point3d(5, 5, 0),
new Point3d(12, 3, 0)))
{

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acLine);
acTrans.AddNewlyCreatedDBObject(acLine, true);
}

// Save the new object to the database
acTrans.Commit();
}
}

创建多段线对象(.NET)

此示例使用二维坐标(2,4)、(4,2)和(6,4)向模型空间添加具有两条直线段的轻量化图元。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
[CommandMethod("AddLightweightPolyline")]
public static void AddLightweightPolyline()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a polyline with two segments (3 points)
using (Polyline acPoly = new Polyline())
{
acPoly.AddVertexAt(0, new Point2d(2, 4), 0, 0, 0);
acPoly.AddVertexAt(1, new Point2d(4, 2), 0, 0, 0);
acPoly.AddVertexAt(2, new Point2d(6, 4), 0, 0, 0);

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acPoly);
acTrans.AddNewlyCreatedDBObject(acPoly, true);
}

// Save the new object to the database
acTrans.Commit();
}
}

创建曲线对象(.NET)

可以使用AutoCAD创建各种曲线对象,包括样条曲线、螺旋线、圆、圆弧和椭圆。所有曲线都在当前UCS的XY平面上创建。

若要创建曲线,请创建以下对象之一的新实例:

  • Arc 弧

    在给定圆心、半径、起始角和终止角的情况下创建圆弧。

  • Circle 圆

    在给定圆心和半径的情况下创建圆。

  • Ellipse 椭圆

    在给定中心点、长轴上的点和半径比的情况下创建椭圆。

  • Spline 样条

    创建二次或三次NURBS(非均匀有理B样条)曲线。

  • Helix 螺旋

    创建二维或三维螺旋对象。

本节中的主题

  • 创建圆对象(.NET)
  • 创建弧形对象(.NET)
  • 创建样条线对象(.NET)

创建圆对象(.NET)

本示例在模型空间中创建一个圆心为(2,3,0)、半径为4.25的圆。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("AddCircle")]
public static void AddCircle()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle that is at 2,3 with a radius of 4.25
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(2, 3, 0);
acCirc.Radius = 4.25;

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);
}

// Save the new object to the database
acTrans.Commit();
}
}

创建弧形对象(.NET)

本示例在模型空间中创建一个圆弧,其中心点为(6.25,9.125,0),半径为6,起始角度为1.117(64度),终止角度为3.5605(204度)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("AddArc")]
public static void AddArc()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create an arc that is at 6.25,9.125 with a radius of 6, and
// starts at 64 degrees and ends at 204 degrees
using (Arc acArc = new Arc(new Point3d(6.25, 9.125, 0),
6, 1.117, 3.5605))
{

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acArc);
acTrans.AddNewlyCreatedDBObject(acArc, true);
}

// Save the new line to the database
acTrans.Commit();
}
}

创建样条线对象(.NET)

此示例使用三个点(0,0,0)、(5,5,0)和(10,0,0)在模型空间中创建圆。样条曲线的起点切线和终点切线为(0.5,0.5,0.0)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("AddSpline")]
public static void AddSpline()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Define the fit points for the spline
Point3dCollection ptColl = new Point3dCollection();
ptColl.Add(new Point3d(0, 0, 0));
ptColl.Add(new Point3d(5, 5, 0));
ptColl.Add(new Point3d(10, 0, 0));

// Get a 3D vector from the point (0.5,0.5,0)
Vector3d vecTan = new Point3d(0.5, 0.5, 0).GetAsVector();

// Create a spline through (0, 0, 0), (5, 5, 0), and (10, 0, 0) with a
// start and end tangency of (0.5, 0.5, 0.0)
using (Spline acSpline = new Spline(ptColl, vecTan, vecTan, 4, 0.0))
{
// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acSpline);
acTrans.AddNewlyCreatedDBObject(acSpline, true);
}

// Save the new line to the database
acTrans.Commit();
}
}

创建点对象(.NET)

Point 对象可能很有用,例如,作为节点或参照点,可以捕捉到这些点或从这些点偏移对象。可以设置点的样式及其相对于屏幕的大小或以绝对单位设置。

Database 对象的 Pdmode 和 Pdsize 属性控制Point对象的外观。如果 Pdmode 的值为0、2、3和4,则指定要通过该点绘制的图形。值为1时,不选择要显示的内容。

img

将32、64或96加到前一个值上,除了通过点绘制的图形外,还可以选择围绕点绘制的形状:

img

Pdsize 控制点图形的大小,但 Pdmode 为0和1时除外。设置为0时,将在图形区域高度的5%处生成点。将 Pdsize 设置为正值可指定点图形的绝对大小。负值被解释为视口大小的百分比。重新生成图形时,将重新计算所有点的大小。

更改 Pdmode 和 Pdsize 后,现有点的外观将在下次重新生成图形时更改。

创建Point对象并更改其外观

以下示例在模型空间中的坐标(5,5,0)处创建 Point 对象。然后更新 Pdmode 和 Pdsize 属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("AddPointAndSetPointStyle")]
public static void AddPointAndSetPointStyle()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a point at (4, 3, 0) in Model space
using (DBPoint acPoint = new DBPoint(new Point3d(4, 3, 0)))
{
// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acPoint);
acTrans.AddNewlyCreatedDBObject(acPoint, true);
}

// Set the style for all point objects in the drawing
acCurDb.Pdmode = 34;
acCurDb.Pdsize = 1;

// Save the new object to the database
acTrans.Commit();
}
}

创建实体填充区域(.NET)

您可以创建用颜色填充的三角形和四边形区域。创建填充区域时,请将FILLMODE系统变量设置为禁用以提高性能,并在创建填充后将其重新设置为启用。

创建四边形实体填充区域时,第三和第四个点的顺序决定其形状。比较以下插图:

img

前两个点定义多边形的一条边。第三个点定义在第二个点的对角位置。如果第四个点设置为等于第三个点,则会创建一个填充三角形。

创建实体填充对象

以下示例使用坐标(0,0,0)、(5,0,0)、(5,8,0)和(0,8,0)在模型空间中创建四边形实体(蝴蝶结)。它还使用坐标(10,0,0)、(15,0,0)、(10,8,0)和(15,8,0)创建矩形形状的四边形实体。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("Add2DSolid")]
public static void Add2DSolid()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a quadrilateral (bow-tie) solid in Model space
using (Solid ac2DSolidBow = new Solid(new Point3d(0, 0, 0),
new Point3d(5, 0, 0),
new Point3d(5, 8, 0),
new Point3d(0, 8, 0)))
{
// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(ac2DSolidBow);
acTrans.AddNewlyCreatedDBObject(ac2DSolidBow, true);
}

// Create a quadrilateral (square) solid in Model space
using (Solid ac2DSolidSqr = new Solid(new Point3d(10, 0, 0),
new Point3d(15, 0, 0),
new Point3d(10, 8, 0),
new Point3d(15, 8, 0)))
{
// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(ac2DSolidSqr);
acTrans.AddNewlyCreatedDBObject(ac2DSolidSqr, true);
}

// Save the new object to the database
acTrans.Commit();
}
}

使用面域(.NET)

面域是您从称为环的闭合形状创建的二维封闭面域。回路是由直线和曲线对象组成的闭合边界,这些对象本身不相交。回路可以是直线、轻型多段线、二维和三维多段线、圆、圆弧、椭圆、椭圆弧、样条曲线、三维面、轨迹和实体的组合。

组成环的对象必须是闭合的,或者通过与其他对象共享端点来形成闭合面域。它们也必须共面(在同一平面上)。组成面域的循环必须定义为对象数组。

本节中的主题

  • 创建面域(.NET)
  • 创建复合面域(.NET)

创建面域(.NET)

通过创建 Region 对象的实例,然后将其附加到 BlockTableRecord 对象,可以将面域添加到 BlockTableRecord 对象。在将其添加到 BlockTableRecord 对象之前,需要根据形成闭合环的对象计算面域。 CreateFromCurves 函数在由输入对象数组形成的每个闭合循环中创建一个面域。 CreateFromCurves 方法返回并需要 DBObjectCollection 对象。

AutoCAD将闭合的二维多段线和平面三维多段线转换为单独的面域,然后转换形成闭合平面环的多段线、直线和曲线。如果两条以上的曲线共享一个端点,则生成的面域可能是任意的。因此,实际上可以使用 CreateFromCurves 方法创建多个面域。您需要将创建的每个面域附加到 BlockTableRecord 对象。

创建简单面域

下面的示例从单个圆创建面域。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("AddRegion")]
public static void AddRegion()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create an in memory circle
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(2, 2, 0);
acCirc.Radius = 5;

// Adds the circle to an object array
DBObjectCollection acDBObjColl = new DBObjectCollection();
acDBObjColl.Add(acCirc);

// Calculate the regions based on each closed loop
DBObjectCollection myRegionColl = new DBObjectCollection();
myRegionColl = Region.CreateFromCurves(acDBObjColl);
Region acRegion = myRegionColl[0] as Region;

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acRegion);
acTrans.AddNewlyCreatedDBObject(acRegion, true);

// Dispose of the in memory circle not appended to the database
}

// Save the new object to the database
acTrans.Commit();
}
}

创建复合面域(.NET)

可以通过减去、合并面域或三维实体或查找面域或三维实体的交点来创建复合面域。然后可以拉伸或旋转复合面域以创建复杂实体。要创建复合面域,请使用 BooleanOperation 方法。

减去面域

当您从一个面域减去另一个面域时,您从第一个面域调用 BooleanOperation 方法。这是要从中减去的面域。例如,要计算平面图需要铺多少地毯,请从地板空间的外边界调用 BooleanOperation 方法,并使用无地毯面域(例如柱子和柜台)作为布尔参数列表中的对象。

合并面域

要合并面域,请调用 BooleanOperation 方法并使用常量 BooleanOperationType.BoolUnite 而不是 BooleanOperationType.BoolSubtract 进行操作。您可以按任意顺序组合联合收割机面域以将它们联合起来。

找到两个面域的交集

要找到两个面域的交集,请使用常量 BooleanOperationType.BoolIntersect 。可以按任意顺序组合联合收割机面域以使其相交。

创建复合面域

下面的示例从两个圆创建两个面域,然后从较大的面域中减去较小的面域以创建轮子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("CreateCompositeRegions")]
public static void CreateCompositeRegions()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create two in memory circles
using (Circle acCirc1 = new Circle())
{
acCirc1.Center = new Point3d(4, 4, 0);
acCirc1.Radius = 2;

using (Circle acCirc2 = new Circle())
{
acCirc2.Center = new Point3d(4, 4, 0);
acCirc2.Radius = 1;

// Adds the circle to an object array
DBObjectCollection acDBObjColl = new DBObjectCollection();
acDBObjColl.Add(acCirc1);
acDBObjColl.Add(acCirc2);

// Calculate the regions based on each closed loop
DBObjectCollection myRegionColl = new DBObjectCollection();
myRegionColl = Region.CreateFromCurves(acDBObjColl);
Region acRegion1 = myRegionColl[0] as Region;
Region acRegion2 = myRegionColl[1] as Region;

// Subtract region 1 from region 2
if (acRegion1.Area > acRegion2.Area)
{
// Subtract the smaller region from the larger one
acRegion1.BooleanOperation(BooleanOperationType.BoolSubtract, acRegion2);
acRegion2.Dispose();

// Add the final region to the database
acBlkTblRec.AppendEntity(acRegion1);
acTrans.AddNewlyCreatedDBObject(acRegion1, true);
}
else
{
// Subtract the smaller region from the larger one
acRegion2.BooleanOperation(BooleanOperationType.BoolSubtract, acRegion1);
acRegion1.Dispose();

// Add the final region to the database
acBlkTblRec.AppendEntity(acRegion2);
acTrans.AddNewlyCreatedDBObject(acRegion2, true);
}

// Dispose of the in memory objects not appended to the database
}
}

// Save the new object to the database
acTrans.Commit();
}
}

创建图案填充(.NET)

闭合边界可以用图案填充。

创建图案填充时,最初不指定要填充的区域。首先,您必须创建 Hatch 对象。完成此操作后,可以指定外部循环,即图案填充的最外边界。然后,可以继续指定图案填充中可能存在的任何内环。

本节中的主题

  • 创建图案填充对象(.NET)
  • 关联图案填充(.NET)
  • 指定填充图案类型和名称(.NET)
  • 定义图案填充边界(.NET)

创建图案填充对象(.NET)

创建 Hatch 对象时,请指定填充图案类型、填充图案名称和关联性。创建图案填充对象后,将无法更改图案填充关联性。

若要创建Hatch对象,请创建该对象的新实例,然后使用 AppendEntity 方法将其添加到 BlockTableRecord 对象。

关联图案填充(.NET)

可以创建关联或非关联图案填充。关联图案填充链接到其边界,并在修改边界时更新。非关联图案填充独立于其边界。

若要使图案填充具有关联性,请将创建的图案填充对象的 Associative 特性设置为 TRUE 。若要使图案填充不关联,请将 Associative 特性设置为 FALSE 。

在附加图案填充循环之前,必须设置图案填充的关联性。如果图案填充对象是非关联的,则可以通过将 Associative 特性设置为 TRUE 并重新附加图案填充循环来使其再次关联。

指定填充图案类型和名称(.NET)

AutoCAD提供了实体填充和五十多种行业标准填充图案。填充图案亮显图形的特定特征或区域。例如,图案可以帮助区分3D对象的组件或表示构成对象的材料。

可以使用AutoCAD提供的阵列或外部阵列库中的阵列。

若要指定唯一的图案,必须同时指定图案填充对象的图案类型和名称。模式类型指定在何处查找模式名称。输入图案类型时,请使用以下常量之一:

  • HatchPatternType.PreDefined

    acad.patacadiso.pat文件中定义的阵列名称中删除阵列名称。

  • HatchPatternType.UserDefined

    使用当前线型定义线型图案。

  • HatchPatternType.CustomDefined

    从除acad.patacadiso.pat文件之外的PAT中删除图案名称。

    输入图案名称时,请使用对图案类型指定的文件有效的名称。

定义图案填充边界(.NET)

创建图案填充对象后,可以添加图案填充边界。边界可以是直线、圆弧、圆、二维多段线、椭圆、样条曲线和面域的任意组合。

添加的第一个边界必须是外边界,它定义了要由图案填充的最外边界。要添加外部边界,请使用 AppendLoop 方法,并将 HatchLoopTypes.Outermost 常量用于要追加的循环类型。

定义外部边界后,可以继续添加其他边界。使用带有 HatchLoopTypes.Default 常量的 AppendLoop 方法添加内部边界。

内部边界定义图案填充内的孤岛。Hatch对象如何处理这些孤岛取决于 HatchStyle 属性的设置。 HatchStyle 属性可以设置为以下条件之一:

图案填充样式定义

HatchStyle Condition Description
img Normal (HatchStyle.Normal) 指定标准样式或法线。该选项从最外侧的面积边界向内填充。如果AutoCAD遇到内部边界,它将关闭图案填充,直到遇到另一个边界。这是 HatchStyle 属性的默认设置。
img Outer (HatchStyle.Outer) 仅填充最外面的区域。此样式也会从区域边界向内填充图案,但如果遇到内部边界,则会关闭图案填充,并且不会再次启用。
img Ignore (HatchStyle.Ignore) 忽略内部结构。此选项将填充所有内部对象。

完成图案填充的定义后,必须先对其进行计算,然后才能显示。使用 EvaluateHatch 方法来执行此操作。

创建图案填充对象

以下示例在模型空间中创建关联的图案填充。创建图案填充后,可以更改与图案填充关联的圆的大小。图案填充将更改以匹配圆的大小。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("AddHatch")]
public static void AddHatch()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle object for the closed boundary to hatch
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(3, 3, 0);
acCirc.Radius = 1;

// Add the new circle object to the block table record and the transaction
acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);

// Adds the circle to an object id array
ObjectIdCollection acObjIdColl = new ObjectIdCollection();
acObjIdColl.Add(acCirc.ObjectId);

// Create the hatch object and append it to the block table record
using (Hatch acHatch = new Hatch())
{
acBlkTblRec.AppendEntity(acHatch);
acTrans.AddNewlyCreatedDBObject(acHatch, true);

// Set the properties of the hatch object
// Associative must be set after the hatch object is appended to the
// block table record and before AppendLoop
acHatch.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31");
acHatch.Associative = true;
acHatch.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl);
acHatch.EvaluateHatch(true);
}
}

// Save the new object to the database
acTrans.Commit();
}
}

使用选择集(.NET)

选择集可以由单个对象组成,也可以是更复杂的分组:例如,某个图层上的对象集。

选择集通常是通过以下方式创建的:在命令启动之前,通过拾取第一选择或在命令处于活动状态时的“选择对象:”提示下,请求用户在绘图区域中选择对象。选择集不是持久性对象,如果需要维护选择集以供多个命令之间使用或将来使用,则需要创建自定义字典,并将在选择集中找到的ObjectId作为软指针记录在字典记录中。

作为将ObjectId存储为软指针的替代方案,您可以将每个对象句柄存储在字典中。然后使用 Database.GetObjectId 方法从存储的句柄中获取对象的ObjectId。

注意:无论你将ObjectId存储为字典中的软指针还是句柄,你都需要在访问它之前确保对象存在。

提示和选择过滤器

选择集的管理被拆分到属于 Autodesk.AutoCAD.EditorInput 命名空间的多个对象中。使用 Editor 对象提示用户进行选择,并执行选择操作。 PromptSelectionOptions 对象用于配置选择操作开始时显示给用户的提示, SelectionFilter 类可用于按实体属性筛选选择集。

PromptSelectionOptions 类提供了用于指定提示关键字的 SetKeywords 方法,以及用于配置提示消息的 MessageForAdding 和 MessageForRemoval 属性。如“ResultBuffer数据类型(.NET)”主题中所述, SelectionFilter 类以 TypedValue 对象数组的形式接受筛选器参数。每个 TypedValue 对象表示一个过滤条件。可以为选择指定任何数量的条件。

当应用程序准备好提示选择时,您可以调用 Editor 对象上的 GetSelection 方法。 Editor.GetSelection 方法存在于许多重载版本中。对于使用标准AutoCAD提示的简单、未过滤的选择,可以使用无参数重载。对于希望提供自定义提示消息(包括关键字)的情况,可以使用接受 PromptSelectionOptions 对象的重载。若要指定筛选器,请使用接受 SelectionFilter 对象的重载。

其他选择方法涵盖了AutoCAD程序中可用的全部选择模式。 Editor.SelectImplied 方法提供对隐含的或先选择的选择集的访问。 Editor.SelectPrevious 方法返回在上一个选择集中选择的对象。像 SelectCrossingWindow 和 SelectFence 这样的方法让应用程序通过窗口、交叉、栅栏和多边形来选择实体。

获取PickFirst选择集(.NET)

在启动命令之前选择对象时,将创建PickFirst选择集。要获得PickFirst选择集的对象,必须满足以下几个条件:

  • PICKFIRST系统变量必须设置为1
  • 必须使用PickFirst选择集的命令定义 UsePickSet 命令标志
  • 调用 SelectImplied 方法以获取PickFirst选择集

SetImpliedSelection 方法用于清除当前PickFirst选择集。

获取PickFirst选择集

此示例显示PickFirst选择集中的对象数,然后请求用户选择其他对象。在请求用户选择对象之前,将使用 SetImpliedSelection 方法清除当前PickFirst选择集。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;

[CommandMethod("CheckForPickfirstSelection", CommandFlags.UsePickSet)]
public static void CheckForPickfirstSelection()
{
// Get the current document
Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

// Get the PickFirst selection set
PromptSelectionResult acSSPrompt;
acSSPrompt = acDocEd.SelectImplied();

SelectionSet acSSet;

// If the prompt status is OK, objects were selected before
// the command was started
if (acSSPrompt.Status == PromptStatus.OK)
{
acSSet = acSSPrompt.Value;

Application.ShowAlertDialog("Number of objects in Pickfirst selection: " +
acSSet.Count.ToString());
}
else
{
Application.ShowAlertDialog("Number of objects in Pickfirst selection: 0");
}

// Clear the PickFirst selection set
ObjectId[] idarrayEmpty = new ObjectId[0];
acDocEd.SetImpliedSelection(idarrayEmpty);

// Request for objects to be selected in the drawing area
acSSPrompt = acDocEd.GetSelection();

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
acSSet = acSSPrompt.Value;

Application.ShowAlertDialog("Number of objects selected: " +
acSSet.Count.ToString());
}
else
{
Application.ShowAlertDialog("Number of objects selected: 0");
}
}

在绘图区域中选择对象(.NET)

可以通过让用户交互选择对象来选择对象,也可以通过AutoCAD .NET API模拟多种对象选择选项。如果您的例程执行多个选择集,则需要跟踪返回的每个选择集,或者创建 ObjectIdCollection 对象来跟踪所有选定对象。使用以下函数可以从图形中选择对象:

获取选择

允许用户从屏幕上拾取对象。

选择全部

显示图形中的所有对象。

注意:所有布局和空间中的对象都将被选中,包括对象将被锁定或冻结。

选择交叉多边形

选择放置在通过指定点定义的多边形内或与该多边形相交的对象。多边形可以是任何形状,但不能交叉或接触自身。

选择交叉窗口

选择由两个点定义的区域内或穿过该区域的对象。

选择围栏

选择与选择栏交叉的所有对象。围栏选择与交叉多边形选择类似,不同之处在于围栏不是闭合的,并且围栏可以自己交叉。

选择最后一个

选择在当前空间中创建的最后一个对象。

选择上一个

选择在上一个“选择对象:”提示期间选择的所有对象。

选择窗口

选择所有完全放置在由两点定义的矩形内的对象。

选择窗口多边形

选择完全放置在由点定义的多边形内的对象。多边形可以是任何形状,但不能交叉或接触自身。

通过点选择

选择通过给定点的对象,并将其放置到活动选择集中。

按多边形选择

选择在围栏内的对象并将其添加到活动选择集中。

提示在屏幕上输入对象并重新选择选择集

此示例提示用户选择对象,然后将每个选定对象的颜色更改为绿色或AutoCAD颜色索引3。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;

[CommandMethod("SelectObjectsOnscreen")]
public static void SelectObjectsOnscreen()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Request for objects to be selected in the drawing area
PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection();

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
SelectionSet acSSet = acSSPrompt.Value;

// Step through the objects in the selection set
foreach (SelectedObject acSSObj in acSSet)
{
// Check to make sure a valid SelectedObject object was returned
if (acSSObj != null)
{
// Open the selected object for write
Entity acEnt = acTrans.GetObject(acSSObj.ObjectId,
OpenMode.ForWrite) as Entity;

if (acEnt != null)
{
// Change the object's color to Green
acEnt.ColorIndex = 3;
}
}
}

// Save the new object to the database
acTrans.Commit();
}

// Dispose of the transaction
}
}

使用交叉窗口选择对象

本示例选择与交叉窗口相交的对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;

[CommandMethod("SelectObjectsByCrossingWindow")]
public static void SelectObjectsByCrossingWindow()
{
// Get the current document editor
Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

// Create a crossing window from (2,2,0) to (10,8,0)
PromptSelectionResult acSSPrompt;
acSSPrompt = acDocEd.SelectCrossingWindow(new Point3d(2, 2, 0),
new Point3d(10, 8, 0));

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
SelectionSet acSSet = acSSPrompt.Value;

Application.ShowAlertDialog("Number of objects selected: " +
acSSet.Count.ToString());
}
else
{
Application.ShowAlertDialog("Number of objects selected: 0");
}
}

选择集关键字(.NET)

应用程序可以在实际创建选择集之前使用关键字提示用户选择首选项。

通过创建 PromptSelectionOptions 对象的实例,可以将关键字分配给对象选择操作。创建 PromptSelectionOptions 对象后,将使用 SetKeywords 方法指定用户可以在命令提示符下输入的每个关键字。一旦将关键字分配给 PromptSelectionOptions 对象,则必须将 PromptSelectionOptions 对象传递给编辑器的 GetSelection 方法。

用户可以在 Select objects: 提示符处输入的关键字的实现由 PromptSelectionOptions.KeywordInput 事件处理程序处理。当用户在结果提示符处输入关键字时,将引发 KeywordInput 事件并调用应用程序的处理程序。

一个 KeywordInput 处理程序接收一个 SelectionTextInputEventArgs 参数,该参数同时作为输入和输出参数。 SelectionTextInputEventArgs 参数的 Input 属性指示所选的关键字。典型的处理程序将此关键字与应用程序的关键字列表中的关键字进行比较,并调用适当的选择方法。如果实体是由selection方法返回的,应用程序会使用 SelectionTextInputEventArgs.AddObjects 方法将这些实体添加到 SelectionTextInputEventArgs 参数中。当原始的 GetSelection 调用返回时,它将选定的实体提供给设置关键字列表的方法。

下面的示例定义了五个关键字,并添加了一个处理程序来支持用户选择的关键字。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
private static void SelectionKeywordInputHandler(object sender, SelectionTextInputEventArgs eSelectionInput)
{
// Gets the current document editor and define other variables for the current scope
Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;
PromptSelectionResult acSSPrompt = null;
SelectionSet acSSet = null;
ObjectId[] acObjIds = null;

// See if the user choose the myFence keyword
switch (eSelectionInput.Input) {
case "myFence":
// Uses the four points to define a fence selection
Point3dCollection ptsFence = new Point3dCollection();
ptsFence.Add(new Point3d(5.0, 5.0, 0.0));
ptsFence.Add(new Point3d(13.0, 15.0, 0.0));
ptsFence.Add(new Point3d(12.0, 9.0, 0.0));
ptsFence.Add(new Point3d(5.0, 5.0, 0.0));

acSSPrompt = acDocEd.SelectFence(ptsFence);
break;
case "myWindow":
// Defines a rectangular window selection
acSSPrompt = acDocEd.SelectWindow(new Point3d(1.0, 1.0, 0.0), new Point3d(30.0, 20.0, 0.0));
break;
case "myWPoly":
// Uses the four points to define a polygon window selection
Point3dCollection ptsPolygon = new Point3dCollection();
ptsPolygon.Add(new Point3d(5.0, 5.0, 0.0));
ptsPolygon.Add(new Point3d(13.0, 15.0, 0.0));
ptsPolygon.Add(new Point3d(12.0, 9.0, 0.0));
ptsPolygon.Add(new Point3d(5.0, 5.0, 0.0));

acSSPrompt = acDocEd.SelectWindowPolygon(ptsPolygon);
break;
case "myLastSel":
// Gets the last object created
acSSPrompt = acDocEd.SelectLast();
break;
case "myPrevSel":
// Gets the previous object selection set
acSSPrompt = acDocEd.SelectPrevious();
break;
}

// If the prompt status is OK, objects were selected and return
if (acSSPrompt != null)
{
if (acSSPrompt.Status == PromptStatus.OK)
{
// Objects were selected, so add them to the current selection
acSSet = acSSPrompt.Value;
acObjIds = acSSet.GetObjectIds();
eSelectionInput.AddObjects(acObjIds);
}
}
}

[CommandMethod("SelectionKeywordInput")]
public static void SelectionKeywordInput()
{
// Gets the current document editor
Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

// Setups the keyword options
PromptSelectionOptions acKeywordOpts = new PromptSelectionOptions();
acKeywordOpts.Keywords.Add("myFence");
acKeywordOpts.Keywords.Add("myWindow");
acKeywordOpts.Keywords.Add("myWPoly");
acKeywordOpts.Keywords.Add("myLastSel");
acKeywordOpts.Keywords.Add("myPrevSel");

// Adds the event handler for keyword input
acKeywordOpts.KeywordInput += new SelectionTextInputEventHandler(SelectionKeywordInputHandler);

// Prompts the user for a selection set
PromptSelectionResult acSSPrompt = acDocEd.GetSelection(acKeywordOpts);

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
// Gets the selection set
SelectionSet acSSet = acSSPrompt.Value;

// Gets the objects from the selection set
ObjectId[] acObjIds = acSSet.GetObjectIds();
Database acCurDb = Application.DocumentManager.MdiActiveDocument.Database;

// Starts a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
try
{
// Gets information about each object
foreach (ObjectId acObjId in acObjIds)
{
Entity acEnt = (Entity)acTrans.GetObject(acObjId, OpenMode.ForWrite, true);
acDocEd.WriteMessage("\nObject selected: " + acEnt.GetType().FullName);

}
}
finally
{
acTrans.Dispose();
}
}
}

// Removes the event handler for keyword input
acKeywordOpts.KeywordInput -= new SelectionTextInputEventHandler(SelectionKeywordInputHandler);
}

添加到或合并多个选择集(.NET)

可以通过创建 ObjectIdCollection 对象,然后将多个选择集的对象ID添加到一起来合并多个选择集。除了向 ObjectIdCollection 对象添加对象ID之外,还可以删除对象ID。一旦所有对象id都添加到 ObjectIdCollection 对象中,您就可以遍历对象id的集合,并根据需要操作每个对象。

将选定对象添加到选择集中

本示例提示用户选择对象两次,然后将创建的两个选择集合并为一个选择集。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;

[CommandMethod("MergeSelectionSets")]
public static void MergeSelectionSets()
{
// Get the current document editor
Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

// Request for objects to be selected in the drawing area
PromptSelectionResult acSSPrompt;
acSSPrompt = acDocEd.GetSelection();

SelectionSet acSSet1;
ObjectIdCollection acObjIdColl = new ObjectIdCollection();

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
// Get the selected objects
acSSet1 = acSSPrompt.Value;

// Append the selected objects to the ObjectIdCollection
acObjIdColl = new ObjectIdCollection(acSSet1.GetObjectIds());
}

// Request for objects to be selected in the drawing area
acSSPrompt = acDocEd.GetSelection();

SelectionSet acSSet2;

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
acSSet2 = acSSPrompt.Value;

// Check the size of the ObjectIdCollection, if zero, then initialize it
if (acObjIdColl.Count == 0)
{
acObjIdColl = new ObjectIdCollection(acSSet2.GetObjectIds());
}
else
{
// Step through the second selection set
foreach (ObjectId acObjId in acSSet2.GetObjectIds())
{
// Add each object id to the ObjectIdCollection
acObjIdColl.Add(acObjId);
}
}
}

Application.ShowAlertDialog("Number of objects selected: " +
acObjIdColl.Count.ToString());
}

定义选择筛选器的规则(.NET)

可以使用选择过滤器限制选择哪些对象并将其添加到选择集中。选择过滤器列表可用于按特性或类型过滤选定对象。例如,您可能希望仅选择蓝色对象或特定图层上的对象。也可以组合联合收割机选择标准。例如,可以创建一个选择过滤器,将选择限制在名为“图案”的图层上的蓝色圆。

注意:过滤识别明确分配给对象的值,而不是层继承的值。例如,如果对象的线型特性设置为ByLayer,并且指定给它的图层设置为隐藏线型;过滤指定为隐藏线型的对象不会选择这些对象,因为它们的线型特性设置为ByLayer。

从选择集中删除对象(.NET)

创建选择集后,可以使用选定对象的对象ID。选择集不允许添加对象ID或从中删除对象ID,但可以使用 ObjectIdCollection 对象将多个选择集合并为单个对象。您可以从 ObjectIdCollection 对象中添加和删除对象ID。使用 Remove 或 RemoveAt 方法从 ObjectIdCollection 对象中删除对象ID。

本节中的主题

  • 使用选择过滤器定义选择集规则(.NET)
  • 在选择筛选器中指定多个条件(.NET)
  • 增加过滤器列表条件的复杂性(.NET)
  • 在选择集筛选条件(.NET)中使用通配符模式
  • 扩展数据过滤器(.NET)

使用选择过滤器定义选择集规则(.NET)

选择筛选器由 TypedValues 形式的参数对组成。 TypedValue 的第一个参数标识过滤器的类型(例如,对象),第二个参数指定您正在过滤的值(例如,圆)。筛选器类型是一个指定要使用的筛选器的通配符组代码。这里列出了一些最常见的过滤器类型。

常用过滤器的编码

DXF code Filter type
0 (or DxfCode.Start) 对象类型(String串)例如“Line”、“Circle”、“Arc”等等。
2 (or DxfCode.BlockName) 块名称(String)插入参照的块名。
8 or (DxfCode.LayerName) 图层名称(String) 例如“Layer 0”。
60 (DxfCode.Visibility) 对象可见性(Integer)Use 0 = visible, 1 = invisible.
62 (or DxfCode.Color) 颜色编号(Integer) 从0到256的数字索引值。零表示BYBLOCK。256表示BYLAYER。负值表示图层已关闭。
67 模型/图纸空间指示器(Integer) 使用0或omitted =模型空间,1 =图纸空间。

为选择集指定单个选择条件

下面的代码提示用户选择要包含在选择集中的对象,并筛选出除圆以外的所有对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
[CommandMethod("FilterSelectionSet")]
public static void FilterSelectionSet()
{
// Get the current document editor
Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

// Create a TypedValue array to define the filter criteria
TypedValue[] acTypValAr = new TypedValue[1];
acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 0);

// Assign the filter criteria to a SelectionFilter object
SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

// Request for objects to be selected in the drawing area
PromptSelectionResult acSSPrompt;
acSSPrompt = acDocEd.GetSelection(acSelFtr);

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
SelectionSet acSSet = acSSPrompt.Value;

Application.ShowAlertDialog("Number of objects selected: " +
acSSet.Count.ToString());
}
else
{
Application.ShowAlertDialog("Number of objects selected: 0");
}
}

在选择筛选器中指定多个条件(.NET)

选择符合三个标准的对象

下面的示例指定了三个筛选选定对象的条件:对象必须是圆形,颜色为蓝色,并且必须位于图层0上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[CommandMethod("FilterBlueCircleOnLayer0")]
public static void FilterBlueCircleOnLayer0()
{
// Get the current document editor
Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

// Create a TypedValue array to define the filter criteria
TypedValue[] acTypValAr = new TypedValue[3];
acTypValAr.SetValue(new TypedValue((int)DxfCode.Color, 5), 0);
acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 1);
acTypValAr.SetValue(new TypedValue((int)DxfCode.LayerName, "0"), 2);

// Assign the filter criteria to a SelectionFilter object
SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

// Request for objects to be selected in the drawing area
PromptSelectionResult acSSPrompt;
acSSPrompt = acDocEd.GetSelection(acSelFtr);

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
SelectionSet acSSet = acSSPrompt.Value;

Application.ShowAlertDialog("Number of objects selected: " +
acSSet.Count.ToString());
}
else
{
Application.ShowAlertDialog("Number of objects selected: 0");
}
}

增加过滤器列表条件的复杂性(.NET)

指定多个选择条件时,AutoCAD假定选定对象必须满足每个条件。你可以用其他方式来限定你的标准。对于数值项,可以指定关系运算(例如,圆的半径必须大于或等于5.0)。对于所有项目,您可以指定逻辑操作(例如 Text 或 MText )。

使用-4\f25 ASCII码或常量 DxfCode.Operator 表示选择过滤器中的关系运算符。运算符表示为字符串。下表显示了允许的关系运算符。

选择集过滤器列表的关系运算符

Operator 操作符 Description 描述
“*” 一切都为真(Always true)
“=” 等于
“!=” 不等于
“/=” 不等于
“<>” 不等于
“<” 小于
“<=” 小于或等于
“>” 大于
“>=” 大于或等于
“&” 按位与(仅限整数组)
“&=” 按位掩码等于(仅限整数组)

选择过滤器中的逻辑运算符也由分组代码或常量 DxfCode.Operator 表示,运算符是一个字符串,但运算符必须成对。开始运算符前面是小于符号(<),结束运算符后面是大于符号(>)。下表列出了选择集筛选中允许的逻辑运算符。

选择集筛选器列表的逻辑分组运算符

Starting operator Encloses Ending operator
“<AND” 一个或多个操作数 “AND>”
“<OR” 一个或多个操作数 “OR>”
“<XOR” 两个操作数 “XOR>”
“<NOT” 一个操作数 “NOT>”

选择半径大于或等于5.0的圆

下面的示例选择半径大于或等于5.0的圆。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[CommandMethod("FilterRelational")]
public static void FilterRelational()
{
// Get the current document editor
Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

// Create a TypedValue array to define the filter criteria
TypedValue[] acTypValAr = new TypedValue[3];
acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 0);
acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, ">="), 1);
acTypValAr.SetValue(new TypedValue(40, 5), 2);

// Assign the filter criteria to a SelectionFilter object
SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

// Request for objects to be selected in the drawing area
PromptSelectionResult acSSPrompt;
acSSPrompt = acDocEd.GetSelection(acSelFtr);

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
SelectionSet acSSet = acSSPrompt.Value;

Application.ShowAlertDialog("Number of objects selected: " +
acSSet.Count.ToString());
}
else
{
Application.ShowAlertDialog("Number of objects selected: 0");
}
}

选择文字或多行文字

下面的示例指定可以选择 Text 或 MText 对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
[CommandMethod("FilterForText")]
public static void FilterForText()
{
// Get the current document editor
Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

// Create a TypedValue array to define the filter criteria
TypedValue[] acTypValAr = new TypedValue[4];
acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "<or"), 0);
acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "TEXT"), 1);
acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "MTEXT"), 2);
acTypValAr.SetValue(new TypedValue((int)DxfCode.Operator, "or>"), 3);

// Assign the filter criteria to a SelectionFilter object
SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

// Request for objects to be selected in the drawing area
PromptSelectionResult acSSPrompt;
acSSPrompt = acDocEd.GetSelection(acSelFtr);

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
SelectionSet acSSet = acSSPrompt.Value;

Application.ShowAlertDialog("Number of objects selected: " +
acSSet.Count.ToString());
}
else
{
Application.ShowAlertDialog("Number of objects selected: 0");
}
}

在选择集筛选条件(.NET)中使用通配符模式

选择筛选器中的符号名称和字符串可以包含通配符模式。

下表确定了AutoCAD可识别的通配符,以及每个通配符在字符串上下文中的含义:

通配符

字符 定义
# (pound) 匹配任何单个数字
@ (at) 匹配任何单个字母字符
. (period) 匹配任何单个非字母数字字符
* (asterisk) 匹配任何字符序列,包括空字符序列,并且可以在搜索模式中的任何位置使用:开头、中间或结尾
? (question mark) 匹配任何单个字符
~ (tilde) 如果它是模式中的第一个字符,则它匹配除模式之外的任何字符
[…] 匹配所包含的任何字符
[~…] 匹配任何未括起来的单个字符
- (hyphen) 在方括号内用于指定单个字符的范围
, (comma) 分离两种模式
` (reverse quote) 转义特殊字符(按字面意思读取下一个字符)

选择文本中出现特定单词的多行文字

下面的示例定义一个选择筛选器,该筛选器选择包含文本字符串“The”的 MText 对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
[CommandMethod("FilterMtextWildcard")]
public static void FilterMtextWildcard()
{
// Get the current document editor
Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

// Create a TypedValue array to define the filter criteria
TypedValue[] acTypValAr = new TypedValue[2];
acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "MTEXT"), 0);
acTypValAr.SetValue(new TypedValue((int)DxfCode.Text, "*The*"), 1);

// Assign the filter criteria to a SelectionFilter object
SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

// Request for objects to be selected in the drawing area
PromptSelectionResult acSSPrompt;
acSSPrompt = acDocEd.GetSelection(acSelFtr);

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
SelectionSet acSSet = acSSPrompt.Value;

Application.ShowAlertDialog("Number of objects selected: " +
acSSet.Count.ToString());
}
else
{
Application.ShowAlertDialog("Number of objects selected: 0");
}
}

扩展数据过滤器(.NET)

外部应用程序可以将文本字符串、数值、三维点、距离和图层名称等数据附着到AutoCAD对象。此数据称为扩展数据。您可以筛选包含指定应用程序的扩展数据的实体。

选择包含扩展数据的圆

以下示例过滤包含由“MY_APP”应用程序添加的扩展数据的圆:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[CommandMethod("FilterXdata")]
public static void FilterXdata()
{
// Get the current document editor
Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

// Create a TypedValue array to define the filter criteria
TypedValue[] acTypValAr = new TypedValue[2];
acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "Circle"), 0);
acTypValAr.SetValue(new TypedValue((int)DxfCode.ExtendedDataRegAppName,
"MY_APP"), 1);

// Assign the filter criteria to a SelectionFilter object
SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

// Request for objects to be selected in the drawing area
PromptSelectionResult acSSPrompt;
acSSPrompt = acDocEd.GetSelection(acSelFtr);

// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
SelectionSet acSSet = acSSPrompt.Value;

Application.ShowAlertDialog("Number of objects selected: " +
acSSet.Count.ToString());
}
else
{
Application.ShowAlertDialog("Number of objects selected: 0");
}
}

编辑命名和2D对象(.NET)

可以使用与每个对象关联的方法和属性修改现有对象。如果修改图形对象的可见属性,请使用 Regen 方法在屏幕上重绘对象。 Regen 方法是 Editor 对象的成员。

本节中的主题

  • 使用命名对象(.NET)
  • 擦除对象(.NET)
  • 复制对象(.NET)
  • 偏移对象(.NET)
  • 转换对象(.NET)
  • 阵列对象(.NET)
  • 延伸和修剪对象(.NET)
  • 分解对象(.NET)
  • 编辑多段线(.NET)
  • 编辑样条曲线(.NET)
  • 编辑图案填充(.NET)

使用命名对象(.NET)

除了AutoCAD使用的图形对象外,图形数据库中还存储有多种类型的非图形对象。这些对象具有与其相关联的描述性名称。例如,块、图层、编组和标注样式都指定了名称,并且在大多数情况下都可以重命名。符号表记录的名称显示在AutoCAD的用户界面中,而对象的对象ID在大多数情况下用于在整个AutoCAD .NET API中引用该对象。

例如,将 LayerTableRecord 对象的对象ID指定给图形对象的“层”属性,而不是指定给 LayerTableRecord 的实际名称。但是,可以使用要访问的层的名称从层表中获取 LayerTableRecord 对象的对象ID。

本节中的主题

  • 清除未引用的命名对象(.NET)
  • 重命名对象(.NET)

清除未引用的命名对象(.NET)

可以随时从数据库中清除未引用的命名对象。不能清除被其他对象引用的命名对象。例如,字体文件可能被文本样式引用,图层可能被该图层上的对象引用。清除可减小图形文件保存到磁盘时的大小。

使用 Purge 方法从图形数据库中清除未参照的对象。 Purge 方法需要一个要以 ObjectIdCollection 或 ObjectIdGraph 对象形式清除的对象列表。传递到 Purge 方法中的 ObjectIdCollection 或 ObjectIdGraph 对象将使用可以从数据库中删除的对象进行更新。在调用 Purge 之后,必须擦除返回的每个对象。

移除所有未引用的图层

下面的示例演示如何从数据库中清除所有未引用的图层。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
[CommandMethod("PurgeUnreferencedLayers")]
public static void PurgeUnreferencedLayers()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

// Create an ObjectIdCollection to hold the object ids for each table record
ObjectIdCollection acObjIdColl = new ObjectIdCollection();

// Step through each layer and add iterator to the ObjectIdCollection
foreach (ObjectId acObjId in acLyrTbl)
{
acObjIdColl.Add(acObjId);
}

// Remove the layers that are in use and return the ones that can be erased
acCurDb.Purge(acObjIdColl);

// Step through the returned ObjectIdCollection
// and erase each unreferenced layer
foreach (ObjectId acObjId in acObjIdColl)
{
SymbolTableRecord acSymTblRec;
acSymTblRec = acTrans.GetObject(acObjId,
OpenMode.ForWrite) as SymbolTableRecord;

try
{
// Erase the unreferenced layer
acSymTblRec.Erase(true);
}
catch (Autodesk.AutoCAD.Runtime.Exception Ex)
{
// Layer could not be deleted
Application.ShowAlertDialog("Error:\n" + Ex.Message);
}
}

// Commit the changes and dispose of the transaction
acTrans.Commit();
}
}

VBA/ActiveX交叉引用

在ActiveX Automation库中,您可以使用 PurgeAll 方法删除所有未引用的命名对象,它将标识可以删除的对象。但是,对于AutoCAD .NET API,您需要提供要清除的对象,然后 Purge 方法将返回实际可以清除的对象。因此,在使用AutoCAD .NET API从数据库中清除所有未引用的命名对象时,需要做更多的工作。

1
ThisDrawing.PurgeAll

重命名对象(.NET)

随着图形变得越来越复杂,可以重命名对象以使名称保持有意义或避免与已插入或附着的其他图形中的名称冲突。Name属性用于获取当前名称或更改命名对象的名称。

可以重命名任何命名对象,但AutoCAD保留的命名对象(例如图层0或CONTINUOUS线型)除外。

名称最长可达255个字符。除了字母和数字之外,名称还可以包含空格(尽管AutoCAD会删除直接出现在名称前后的空格)以及Microsoft® Windows®或AutoCAD未用于其他目的的任何特殊字符。不能使用的特殊字符包括小于号和大于号(<>)、正斜线和反斜线(/ \)、引号(“)、冒号(:)、分号(;)、问号(?)、逗号(,)、空格(*)、竖线(|)、等号(=)和单引号(’)。也不能使用Unicode字体创建的特殊字符。

重命名图层

此示例创建图层“0”的副本,并将新图层重命名为“MyLayer”。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
[CommandMethod("RenameLayer")]
public static void RenameLayer()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Returns the layer table for the current database
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForWrite) as LayerTable;

// Clone layer 0 (copy it and its properties) as a new layer
LayerTableRecord acLyrTblRec;
acLyrTblRec = acTrans.GetObject(acLyrTbl["0"],
OpenMode.ForRead).Clone() as LayerTableRecord;

// Change the name of the cloned layer
acLyrTblRec.Name = "MyLayer";

// Add the cloned layer to the Layer table and transaction
acLyrTbl.Add(acLyrTblRec);
acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);

// Save changes and dispose of the transaction
acTrans.Commit();
}
}

擦除对象(.NET)

您可以使用 Erase 方法删除非图形和图形对象。

注意:虽然许多非图形对象(如层表和模型空间块表记录)都有 Erase 方法,但不应调用该方法。如果在其中一个对象上调用 Erase ,则会发生错误。

创建和擦除一个多段线

此示例创建一个轻量级的多段线,然后将其擦除。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
[CommandMethod("EraseObject")]
public static void EraseObject()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a lightweight polyline
using (Polyline acPoly = new Polyline())
{
acPoly.AddVertexAt(0, new Point2d(2, 4), 0, 0, 0);
acPoly.AddVertexAt(1, new Point2d(4, 2), 0, 0, 0);
acPoly.AddVertexAt(2, new Point2d(6, 4), 0, 0, 0);

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acPoly);
acTrans.AddNewlyCreatedDBObject(acPoly, true);

// Update the display and display an alert message
acDoc.Editor.Regen();
Application.ShowAlertDialog("Erase the newly added polyline.");

// Erase the polyline from the drawing
acPoly.Erase(true);
}

// Save the new object to the database
acTrans.Commit();
}
}

复制对象(.NET)

您可以在数据库中创建大多数非图形对象和图形对象的副本。您可以使用 Clone 函数创建对象的副本。克隆对象后,可以在将返回的对象添加到数据库之前对其进行修改。通过使用 Clone 和 TransformBy 方法,可以模拟AutoCAD中的许多修改命令。

沿着创建对象的直接副本,还可以使用 Clone 和 TransformBy 方法来偏移、镜像和阵列对象。

本节中的主题

  • (.NET) 复制对象(.NET)
  • 在Database之间复制对象(.NET)

复制对象(.NET)

要复制对象,请使用为该对象提供的 Clone 函数。此方法创建一个新对象,该对象是原始对象的副本。创建重复对象后,可以在将其添加或追加到数据库之前对其进行修改。如果不变换对象或更改其位置,则新对象将位于与原始对象相同的位置。

如果您可能想要复制大量对象,则可以将每个对象ID添加到 ObjectIdCollection 对象,然后重新配置每个对象。当您重新定义每个对象时,您可以对每个对象使用 Clone 函数,然后将新对象添加或追加到数据库中。

复制单个对象

下面的示例创建一个新圆,然后创建该圆的直接副本以创建第二个圆。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
[CommandMethod("SingleCopy")]
public static void SingleCopy()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle that is at 2,3 with a radius of 4.25
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(2, 3, 0);
acCirc.Radius = 4.25;

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);

// Create a copy of the circle and change its radius
Circle acCircClone = acCirc.Clone() as Circle;
acCircClone.Radius = 1;

// Add the cloned circle
acBlkTblRec.AppendEntity(acCircClone);
acTrans.AddNewlyCreatedDBObject(acCircClone, true);
}

// Save the new object to the database
acTrans.Commit();
}
}

复制多个对象

下面的示例使用 ObjectIdCollection 对象来跟踪应复制的对象。一旦对象id被添加到集合中,集合将被迭代,新对象将使用 Clone 方法创建,然后添加到模型空间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
[CommandMethod("MultipleCopy")]
public static void MultipleCopy()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle that is at (0,0,0) with a radius of 5
using (Circle acCirc1 = new Circle())
{
acCirc1.Center = new Point3d(0, 0, 0);
acCirc1.Radius = 5;

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acCirc1);
acTrans.AddNewlyCreatedDBObject(acCirc1, true);

// Create a circle that is at (0,0,0) with a radius of 7
using (Circle acCirc2 = new Circle())
{
acCirc2.Center = new Point3d(0, 0, 0);
acCirc2.Radius = 7;

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acCirc2);
acTrans.AddNewlyCreatedDBObject(acCirc2, true);

// Add all the objects to clone
DBObjectCollection acDBObjColl = new DBObjectCollection();
acDBObjColl.Add(acCirc1);
acDBObjColl.Add(acCirc2);

foreach (Entity acEnt in acDBObjColl)
{
Entity acEntClone;
acEntClone = acEnt.Clone() as Entity;
acEntClone.ColorIndex = 1;

// Create a matrix and move each copied entity 15 units
acEntClone.TransformBy(Matrix3d.Displacement(new Vector3d(15, 0, 0)));

// Add the cloned object
acBlkTblRec.AppendEntity(acEntClone);
acTrans.AddNewlyCreatedDBObject(acEntClone, true);
}
}
}

// Save the new object to the database
acTrans.Commit();
}
}

在Database之间复制对象(.NET)

可以在两个数据库之间复制对象。 Clone 函数用于复制同一数据库中的对象,而 WblockCloneObjects 方法用于将对象从一个数据库复制到另一个数据库。 WblockCloneObjects 方法是 Database 对象的成员。 WblockCloneObjects 方法需要以下参数:

  • ObjectIdCollection-要克隆的对象的列表。
  • ObjectId-正在克隆的对象的新父对象的ObjectId。
  • IdMapping-正在克隆的对象的当前和新ObjectId的数据结构。
  • DuplicateRecordCloning-确定应如何处理重复对象。
  • Defer Translation - 控制是否应转换对象ID。

将对象从一个数据库复制到另一个数据库

此示例创建两个Circle对象,然后使用 WblockCloneObjects 方法将圆复制到新图形中。该示例还在复制圆之前使用acad.dwt文件创建新图形。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
[CommandMethod("CopyObjectsBetweenDatabases", CommandFlags.Session)]
public static void CopyObjectsBetweenDatabases()
{
ObjectIdCollection acObjIdColl = new ObjectIdCollection();

// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Lock the current document
using (DocumentLock acLckDocCur = acDoc.LockDocument())
{
// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table record for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle that is at (0,0,0) with a radius of 5
using (Circle acCirc1 = new Circle())
{
acCirc1.Center = new Point3d(0, 0, 0);
acCirc1.Radius = 5;

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acCirc1);
acTrans.AddNewlyCreatedDBObject(acCirc1, true);

// Create a circle that is at (0,0,0) with a radius of 7
using (Circle acCirc2 = new Circle())
{
acCirc2.Center = new Point3d(0, 0, 0);
acCirc2.Radius = 7;

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acCirc2);
acTrans.AddNewlyCreatedDBObject(acCirc2, true);

// Add all the objects to copy to the new document
acObjIdColl = new ObjectIdCollection();
acObjIdColl.Add(acCirc1.ObjectId);
acObjIdColl.Add(acCirc2.ObjectId);
}
}

// Save the new objects to the database
acTrans.Commit();
}

// Unlock the document
}

// Change the file and path to match a drawing template on your workstation
string sLocalRoot = Application.GetSystemVariable("LOCALROOTPREFIX") as string;
string sTemplatePath = sLocalRoot + "Template\\acad.dwt";

// Create a new drawing to copy the objects to
DocumentCollection acDocMgr = Application.DocumentManager;
Document acNewDoc = acDocMgr.Add(sTemplatePath);
Database acDbNewDoc = acNewDoc.Database;

// Lock the new document
using (DocumentLock acLckDoc = acNewDoc.LockDocument())
{
// Start a transaction in the new database
using (Transaction acTrans = acDbNewDoc.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTblNewDoc;
acBlkTblNewDoc = acTrans.GetObject(acDbNewDoc.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for read
BlockTableRecord acBlkTblRecNewDoc;
acBlkTblRecNewDoc = acTrans.GetObject(acBlkTblNewDoc[BlockTableRecord.ModelSpace],
OpenMode.ForRead) as BlockTableRecord;

// Clone the objects to the new database
IdMapping acIdMap = new IdMapping();
acCurDb.WblockCloneObjects(acObjIdColl, acBlkTblRecNewDoc.ObjectId, acIdMap,
DuplicateRecordCloning.Ignore, false);

// Save the copied objects to the database
acTrans.Commit();
}

// Unlock the document
}

// Set the new document current
acDocMgr.MdiActiveDocument = acNewDoc;
}

偏移对象(.NET)

偏移对象将在距原始对象指定的偏移距离处创建新对象。可以偏移圆弧、圆、椭圆、直线、轻型多段线、多段线、样条曲线和构造线。

要偏移对象,请使用为该对象提供的 GetOffsetCurves 方法。该函数需要一个正或负的距离数值来偏移对象。如果距离为负,AutoCAD会将其解释为偏移,以生成“较小”曲线(即,对于圆弧,它将偏移到小于起始曲线半径的给定距离的半径)。如果“较小”没有意义,则AutoCAD将在较小的X、Y、ZWCS坐标方向上偏移。

对于许多对象,此操作的结果将是一条新曲线(可能与原始曲线的类型不同)。例如,偏移椭圆将生成样条曲线,因为结果确实符合椭圆的方程。在某些情况下,可能需要偏移结果为多条曲线。因此,该函数返回一个 DBObjectCollection 对象,其中包含通过偏移曲线创建的所有对象。返回的 DBObjectCollection 对象需要为创建的每个对象迭代,然后附加到图形数据库。

偏移一条多段线

此示例创建一条多段线图元,然后将其偏移。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
[CommandMethod("OffsetObject")]
public static void OffsetObject()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a lightweight polyline
using (Polyline acPoly = new Polyline())
{
acPoly.AddVertexAt(0, new Point2d(1, 1), 0, 0, 0);
acPoly.AddVertexAt(1, new Point2d(1, 2), 0, 0, 0);
acPoly.AddVertexAt(2, new Point2d(2, 2), 0, 0, 0);
acPoly.AddVertexAt(3, new Point2d(3, 2), 0, 0, 0);
acPoly.AddVertexAt(4, new Point2d(4, 4), 0, 0, 0);
acPoly.AddVertexAt(5, new Point2d(4, 1), 0, 0, 0);

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acPoly);
acTrans.AddNewlyCreatedDBObject(acPoly, true);

// Offset the polyline a given distance
DBObjectCollection acDbObjColl = acPoly.GetOffsetCurves(0.25);

// Step through the new objects created
foreach (Entity acEnt in acDbObjColl)
{
// Add each offset object
acBlkTblRec.AppendEntity(acEnt);
acTrans.AddNewlyCreatedDBObject(acEnt, true);
}
}

// Save the new objects to the database
acTrans.Commit();
}
}

转换对象(.NET)

您可以使用由 Matrix3d 对象和 TransformBy 方法表示的4 x 4变换矩阵来移动、缩放、旋转和镜像对象。您还可以使用 GetTransformedCopy 方法创建实体的副本,然后将转换应用于副本。 Matrix3d 对象是 Geometry 命名空间的一部分。

矩阵的前三列指定缩放和旋转。矩阵的第四列是平移向量。下表演示了变换矩阵配置,其中R =旋转,T =平移:

变换矩阵配置

R00 R01 R02 T0
R10 R11 R12 T1
R20 R21 R22 T2
0 0 0 1

要转换一个对象,首先初始化一个 Matrix3d 对象。可以使用双精度数数组初始化变换矩阵,也可以从表示世界坐标系或用户坐标系的矩阵开始。初始化后,您可以使用 Matrix3d 对象的函数来修改矩阵的缩放、旋转或位移变换。

完成变换矩阵后,使用 TransformBy 方法将矩阵应用于对象。下面的代码行演示了将矩阵( dMatrix )应用于对象( acObj ):

1
acObj.TransformBy(dMatrix);

旋转矩阵的示例

下面显示了一个用于定义变换矩阵的数据数组,该数组被分配给变量 dMatrix ,该变量将使图元绕点(0,0,0)旋转90度。

旋转矩阵:绕点(0,0,0)90度

0.0 -1.0 0.0 0.0
1.0 0.0 0.0 0.0
0.0 0.0 1.0 0.0
0.0 0.0 0.0 1.0

C#

使用数据数组初始化变换矩阵,其中包含将对象旋转90度的信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
double[] dMatrix = new double[16];

dMatrix[0] = 0.0;
dMatrix[1] = -1.0;
dMatrix[2] = 0.0;
dMatrix[3] = 0.0;
dMatrix[4] = 1.0;
dMatrix[5] = 0.0;
dMatrix[6] = 0.0;
dMatrix[7] = 0.0;
dMatrix[8] = 0.0;
dMatrix[9] = 0.0;
dMatrix[10] = 1.0;
dMatrix[11] = 0.0;
dMatrix[12] = 0.0;
dMatrix[13] = 0.0;
dMatrix[14] = 0.0;
dMatrix[15] = 1.0;

Matrix3d acMat3d = new Matrix3d(dMatrix);

初始化一个没有数据数组的变换矩阵,并使用 Rotation 函数返回一个将对象旋转90度的变换矩阵。

1
2
3
4
5
Matrix3d acMat3d = new Matrix3d();

acMat3d = Matrix3d.Rotation(Math.PI / 2,
curUCS.Zaxis,
new Point3d(0, 0, 0));

变换矩阵的其他示例

以下是转换矩阵的更多示例:

旋转矩阵:关于点(5,5,0)的45度

0.707107 -0.707107 0.0 5.0
0.707107 0.707107 0.0 -2.071068
0.0 0.0 1.0 0.0
0.0 0.0 0.0 1.0

平移矩阵:将实体移动(10,10,0)

1.0 0.0 0.0 10.0
0.0 1.0 0.0 10.0
0.0 0.0 1.0 0.0
0.0 0.0 0.0 1.0

缩放矩阵:在点(0,0,0)处缩放10,10

10.0 0.0 0.0 0.0
0.0 10.0 0.0 0.0
0.0 0.0 10.0 0.0
0.0 0.0 0.0 1.0

缩放矩阵:在点(2,2,0)处缩放10,10

10.0 0.0 0.0 -18.0
0.0 10.0 0.0 -18.0
0.0 0.0 10.0 0.0
0.0 0.0 0.0 1.0

本节中的主题

  • 移动对象(.NET)
  • 旋转对象(.NET)
  • 镜像对象(.NET)
  • 缩放对象(.NET)

移动对象(.NET)

可以沿指定矢量沿着移动所有图形对象和属性参照对象。

要移动对象,请使用变换矩阵的 Displacement 功能。这个函数需要一个 Vector3d 对象作为输入。如果你不知道你需要的向量,你可以创建一个 Point3d 对象,然后使用 GetVectorTo 方法返回两点之间的向量。位移向量指示给定对象要移动多远以及向哪个方向移动。

img

沿着向量移动圆

本示例创建一个圆,然后将该圆沿X轴沿着移动两个单位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
[CommandMethod("MoveObject")]
public static void MoveObject()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle that is at 2,2 with a radius of 0.5
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(2, 2, 0);
acCirc.Radius = 0.5;

// Create a matrix and move the circle using a vector from (0,0,0) to (2,0,0)
Point3d acPt3d = new Point3d(0, 0, 0);
Vector3d acVec3d = acPt3d.GetVectorTo(new Point3d(2, 0, 0));

acCirc.TransformBy(Matrix3d.Displacement(acVec3d));

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);
}

// Save the new objects to the database
acTrans.Commit();
}
}

旋转对象(.NET)

可以旋转所有图形对象和属性参照对象。

要旋转对象,请使用变换矩阵的 Rotation 功能。此函数需要一个以弧度表示的旋转角度、一个旋转轴和一个基点。旋转轴必须表示为 Vector3d 对象,基点必须表示为 Point3d 对象。此角度确定对象相对于其当前位置绕基点旋转的距离。

img

围绕基点旋转多段线

此示例创建一个闭合的多段线,然后将对象围绕基点(4,4.25,0)旋转45度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
[CommandMethod("RotateObject")]
public static void RotateObject()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a lightweight polyline
using (Polyline acPoly = new Polyline())
{
acPoly.AddVertexAt(0, new Point2d(1, 2), 0, 0, 0);
acPoly.AddVertexAt(1, new Point2d(1, 3), 0, 0, 0);
acPoly.AddVertexAt(2, new Point2d(2, 3), 0, 0, 0);
acPoly.AddVertexAt(3, new Point2d(3, 3), 0, 0, 0);
acPoly.AddVertexAt(4, new Point2d(4, 4), 0, 0, 0);
acPoly.AddVertexAt(5, new Point2d(4, 2), 0, 0, 0);

// Close the polyline
acPoly.Closed = true;

Matrix3d curUCSMatrix = acDoc.Editor.CurrentUserCoordinateSystem;
CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d;

// Rotate the polyline 45 degrees, around the Z-axis of the current UCS
// using a base point of (4,4.25,0)
acPoly.TransformBy(Matrix3d.Rotation(0.7854,
curUCS.Zaxis,
new Point3d(4, 4.25, 0)));

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acPoly);
acTrans.AddNewlyCreatedDBObject(acPoly, true);
}

// Save the new objects to the database
acTrans.Commit();
}
}

镜像对象(.NET)

镜像沿轴或镜像线沿着翻转对象。可以镜像所有图形对象。

要镜像对象,请使用变换矩阵的 Mirroring 功能。此函数需要一个 Point3d 、 Plane 或 Line3d 对象来定义镜像线。由于镜像是使用变换矩阵完成的,因此不会创建新对象。如果要保留原始对象,则需要先创建对象的副本,然后再对其进行镜像。

img

若要管理 Text 对象的反射特性,请使用MIRTEXT系统变量。MIRRTEXT的默认设置为On(1),这会导致 Text 对象像任何其他对象一样被镜像。当MIRRTEXT为Off(0)时,不镜像文本。使用 GetSystemVariable 和 SetSystemVariable 方法查询并设置MIRRText设置。

img

可以在图纸空间中镜像视口对象,尽管这样做对其模型空间视图或模型空间对象没有影响。

绕轴镜像多段线

此示例创建了一个多段线,并围绕一个轴镜像该镜像。新创建的颜色为蓝色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
[CommandMethod("MirrorObject")]
public static void MirrorObject()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a lightweight polyline
using (Polyline acPoly = new Polyline())
{
acPoly.AddVertexAt(0, new Point2d(1, 1), 0, 0, 0);
acPoly.AddVertexAt(1, new Point2d(1, 2), 0, 0, 0);
acPoly.AddVertexAt(2, new Point2d(2, 2), 0, 0, 0);
acPoly.AddVertexAt(3, new Point2d(3, 2), 0, 0, 0);
acPoly.AddVertexAt(4, new Point2d(4, 4), 0, 0, 0);
acPoly.AddVertexAt(5, new Point2d(4, 1), 0, 0, 0);

// Create a bulge of -2 at vertex 1
acPoly.SetBulgeAt(1, -2);

// Close the polyline
acPoly.Closed = true;

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acPoly);
acTrans.AddNewlyCreatedDBObject(acPoly, true);

// Create a copy of the original polyline
Polyline acPolyMirCopy = acPoly.Clone() as Polyline;
acPolyMirCopy.ColorIndex = 5;

// Define the mirror line
Point3d acPtFrom = new Point3d(0, 4.25, 0);
Point3d acPtTo = new Point3d(4, 4.25, 0);
Line3d acLine3d = new Line3d(acPtFrom, acPtTo);

// Mirror the polyline across the X axis
acPolyMirCopy.TransformBy(Matrix3d.Mirroring(acLine3d));

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acPolyMirCopy);
acTrans.AddNewlyCreatedDBObject(acPolyMirCopy, true);
}

// Save the new objects to the database
acTrans.Commit();
}
}

缩放对象(.NET)

可以通过基于当前图形单位指定基点和比例因子来缩放对象。可以缩放所有图形对象以及属性参照对象。

要缩放对象,请使用变换矩阵的 Scaling 功能。此函数要求对象的比例因子为数值,缩放操作的基点为 Point3d 对象。 Scaling 函数在X、Y和Z方向上均匀缩放对象。对象的尺寸将乘以比例因子。比例因子大于1将放大对象。比例因子介于0和1之间时,对象会缩小。

注意:如果需要不均匀地缩放对象,则需要使用适当的数据数组初始化变换矩阵,然后使用对象的 TransformBy 方法。

缩放多段线

此示例创建一个封闭的轻量化对象,然后从基点(4,4.25,0)将对象缩放0.5。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
[CommandMethod("ScaleObject")]
public static void ScaleObject()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a lightweight polyline
using (Polyline acPoly = new Polyline())
{
acPoly.AddVertexAt(0, new Point2d(1, 2), 0, 0, 0);
acPoly.AddVertexAt(1, new Point2d(1, 3), 0, 0, 0);
acPoly.AddVertexAt(2, new Point2d(2, 3), 0, 0, 0);
acPoly.AddVertexAt(3, new Point2d(3, 3), 0, 0, 0);
acPoly.AddVertexAt(4, new Point2d(4, 4), 0, 0, 0);
acPoly.AddVertexAt(5, new Point2d(4, 2), 0, 0, 0);

// Close the polyline
acPoly.Closed = true;

// Reduce the object by a factor of 0.5
// using a base point of (4,4.25,0)
acPoly.TransformBy(Matrix3d.Scaling(0.5, new Point3d(4, 4.25, 0)));

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acPoly);
acTrans.AddNewlyCreatedDBObject(acPoly, true);
}

// Save the new objects to the database
acTrans.Commit();
}
}

阵列对象(.NET)

可以创建对象的环形阵列或矩形阵列。对象阵列不是使用一组专用函数创建的,而是通过复制对象,然后使用变换矩阵旋转和移动复制的对象的组合来创建的。下面概述了每种类型的阵列的基本逻辑:

环形阵列。复制要阵列的对象,并基于围绕基点的角度移动它。从对象到阵列基点的距离用于计算创建的每个副本的放置。移动复制的对象后,可以根据对象相对于基点的角度旋转对象。创建每个副本后,需要将其追加到块表记录中。

img

矩形阵列。根据所需的行数和列数将对象复制到阵列中。复制对象的复制距离基于行和列之间的指定距离。您首先要创建的副本数量要与原件的第一行或第一列相同。创建第一行或第一列后,可以根据创建的第一行或第一列为其余行或列创建对象数。创建每个副本后,需要将其追加到块表记录中。

img

本节中的主题

  • 创建环形阵列(.NET)
  • 创建矩形阵列(.NET)

创建环形阵列(.NET)

此示例创建一个圆,然后执行圆的环形阵列。这将创建四个围绕基点(4,4,0)填充180度的圆。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
static Point2d PolarPoints(Point2d pPt, double dAng, double dDist)
{
return new Point2d(pPt.X + dDist * Math.Cos(dAng),
pPt.Y + dDist * Math.Sin(dAng));
}

[CommandMethod("PolarArrayObject")]
public static void PolarArrayObject()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table record for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle that is at 2,2 with a radius of 1
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(2, 2, 0);
acCirc.Radius = 1;

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);

// Create a 4 object polar array that goes a 180
int nCount = 1;

// Set a value in radians for 60 degrees
double dAng = 1.0472;

// Use (4,4,0) as the base point for the array
Point2d acPt2dArrayBase = new Point2d(4, 4);

while (nCount < 4)
{
Entity acEntClone = acCirc.Clone() as Entity;

Extents3d acExts;
Point2d acPtObjBase;

// Typically the upper-left corner of an object's extents is used
// for the point on the object to be arrayed unless it is
// an object like a circle.
Circle acCircArrObj = acEntClone as Circle;

if (acCircArrObj != null)
{
acPtObjBase = new Point2d(acCircArrObj.Center.X,
acCircArrObj.Center.Y);
}
else
{
acExts = acEntClone.Bounds.GetValueOrDefault();
acPtObjBase = new Point2d(acExts.MinPoint.X,
acExts.MaxPoint.Y);
}

double dDist = acPt2dArrayBase.GetDistanceTo(acPtObjBase);
double dAngFromX = acPt2dArrayBase.GetVectorTo(acPtObjBase).Angle;

Point2d acPt2dTo = PolarPoints(acPt2dArrayBase,
(nCount * dAng) + dAngFromX,
dDist);

Vector2d acVec2d = acPtObjBase.GetVectorTo(acPt2dTo);
Vector3d acVec3d = new Vector3d(acVec2d.X, acVec2d.Y, 0);
acEntClone.TransformBy(Matrix3d.Displacement(acVec3d));

/*
// The following code demonstrates how to rotate each object like
// the ARRAY command does.
acExts = acEntClone.Bounds.GetValueOrDefault();
acPtObjBase = new Point2d(acExts.MinPoint.X,
acExts.MaxPoint.Y);

// Rotate the cloned entity around its upper-left extents point
Matrix3d curUCSMatrix = acDoc.Editor.CurrentUserCoordinateSystem;
CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d;
acEntClone.TransformBy(Matrix3d.Rotation(nCount * dAng,
curUCS.Zaxis,
new Point3d(acPtObjBase.X,
acPtObjBase.Y, 0)));
*/

acBlkTblRec.AppendEntity(acEntClone);
acTrans.AddNewlyCreatedDBObject(acEntClone, true);

nCount = nCount + 1;
}
}

// Save the new objects to the database
acTrans.Commit();
}
}

创建矩形阵列(.NET)

此示例创建一个圆,然后执行圆的矩形阵列,创建五行和五列圆。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
static Point2d PolarPoints(Point2d pPt, double dAng, double dDist)
{
return new Point2d(pPt.X + dDist * Math.Cos(dAng),
pPt.Y + dDist * Math.Sin(dAng));
}

[CommandMethod("RectangularArrayObject")]
public static void RectangularArrayObject()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table record for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle that is at 2,2 with a radius of 0.5
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(2, 2, 0);
acCirc.Radius = 0.5;

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);

// Create a rectangular array with 5 rows and 5 columns
int nRows = 5;
int nColumns = 5;

// Set the row and column offsets along with the base array angle
double dRowOffset = 1;
double dColumnOffset = 1;
double dArrayAng = 0;

// Get the angle from X for the current UCS
Matrix3d curUCSMatrix = acDoc.Editor.CurrentUserCoordinateSystem;
CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d;
Vector2d acVec2dAng = new Vector2d(curUCS.Xaxis.X,
curUCS.Xaxis.Y);

// If the UCS is rotated, adjust the array angle accordingly
dArrayAng = dArrayAng + acVec2dAng.Angle;

// Use the upper-left corner of the objects extents for the array base point
Extents3d acExts = acCirc.Bounds.GetValueOrDefault();
Point2d acPt2dArrayBase = new Point2d(acExts.MinPoint.X,
acExts.MaxPoint.Y);

// Track the objects created for each column
DBObjectCollection acDBObjCollCols = new DBObjectCollection();
acDBObjCollCols.Add(acCirc);

// Create the number of objects for the first column
int nColumnsCount = 1;
while (nColumns > nColumnsCount)
{
Entity acEntClone = acCirc.Clone() as Entity;
acDBObjCollCols.Add(acEntClone);

// Caclucate the new point for the copied object (move)
Point2d acPt2dTo = PolarPoints(acPt2dArrayBase,
dArrayAng,
dColumnOffset * nColumnsCount);

Vector2d acVec2d = acPt2dArrayBase.GetVectorTo(acPt2dTo);
Vector3d acVec3d = new Vector3d(acVec2d.X, acVec2d.Y, 0);
acEntClone.TransformBy(Matrix3d.Displacement(acVec3d));

acBlkTblRec.AppendEntity(acEntClone);
acTrans.AddNewlyCreatedDBObject(acEntClone, true);

nColumnsCount = nColumnsCount + 1;
}

// Set a value in radians for 90 degrees
double dAng = Math.PI / 2;

// Track the objects created for each row and column
DBObjectCollection acDBObjCollLvls = new DBObjectCollection();

foreach (DBObject acObj in acDBObjCollCols)
{
acDBObjCollLvls.Add(acObj);
}

// Create the number of objects for each row
foreach (Entity acEnt in acDBObjCollCols)
{
int nRowsCount = 1;

while (nRows > nRowsCount)
{
Entity acEntClone = acEnt.Clone() as Entity;
acDBObjCollLvls.Add(acEntClone);

// Caclucate the new point for the copied object (move)
Point2d acPt2dTo = PolarPoints(acPt2dArrayBase,
dArrayAng + dAng,
dRowOffset * nRowsCount);

Vector2d acVec2d = acPt2dArrayBase.GetVectorTo(acPt2dTo);
Vector3d acVec3d = new Vector3d(acVec2d.X, acVec2d.Y, 0);
acEntClone.TransformBy(Matrix3d.Displacement(acVec3d));

acBlkTblRec.AppendEntity(acEntClone);
acTrans.AddNewlyCreatedDBObject(acEntClone, true);

nRowsCount = nRowsCount + 1;
}
}
}

// Save the new objects to the database
acTrans.Commit();
}
}

延伸和修剪对象(.NET)

您可以更改弧的角度,也可以更改直线、开放多段线、椭圆弧和开放样条曲线的长度。结果与延伸和修剪对象类似。

可以通过编辑对象的属性来延伸或修剪对象。例如,要延长一条线,只需更改 StartPoint 或 EndPoint 属性的坐标。若要更改圆弧的角度,请更改圆弧的 StartAngle 或 EndAngle 属性。更改对象的特性后,可能需要重新生成显示以查看图形窗口中的更改。

加长一条线

此示例创建一条直线,然后更改该直线的端点,从而生成一条较长的直线。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
[CommandMethod("ExtendObject")]
public static void ExtendObject()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a line that starts at (4,4,0) and ends at (7,7,0)
using (Line acLine = new Line(new Point3d(4, 4, 0),
new Point3d(7, 7, 0)))
{

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acLine);
acTrans.AddNewlyCreatedDBObject(acLine, true);

// Update the display and diaplay a message box
acDoc.Editor.Regen();
Application.ShowAlertDialog("Before extend");

// Double the length of the line
acLine.EndPoint = acLine.EndPoint + acLine.Delta;
}

// Save the new object to the database
acTrans.Commit();
}
}

分解对象(.NET)

分解对象会将单个对象转换为其组成部分。使用 Explode 函数分解对象,它需要一个用于返回结果对象的 DBObjectCollection 对象。例如,分解对象可能导致创建包含多条直线和圆弧的对象集合。

如果块被分解,则返回的对象集合将保存用于定义块的图形对象。对象分解后,原始对象保持不变。如果希望返回的对象替换原始对象,则必须删除原始对象,然后必须将返回的对象添加到块表记录中。

分解一个多段线

此示例创建一个多段线,然后将对象分解为最简单的对象。分解对象后,将对其进行处理,并将返回的对象添加到模型空间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
[CommandMethod("ExplodeObject")]
public static void ExplodeObject()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a lightweight polyline
using (Polyline acPoly = new Polyline())
{
acPoly.AddVertexAt(0, new Point2d(1, 1), 0, 0, 0);
acPoly.AddVertexAt(1, new Point2d(1, 2), 0, 0, 0);
acPoly.AddVertexAt(2, new Point2d(2, 2), 0, 0, 0);
acPoly.AddVertexAt(3, new Point2d(3, 2), 0, 0, 0);
acPoly.AddVertexAt(4, new Point2d(4, 4), 0, 0, 0);
acPoly.AddVertexAt(5, new Point2d(4, 1), 0, 0, 0);

// Sets the bulge at index 3
acPoly.SetBulgeAt(3, -0.5);

// Explodes the polyline
DBObjectCollection acDBObjColl = new DBObjectCollection();
acPoly.Explode(acDBObjColl);

foreach (Entity acEnt in acDBObjColl)
{
// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acEnt);
acTrans.AddNewlyCreatedDBObject(acEnt, true);
}

// Dispose of the in memory polyline
}

// Save the new objects to the database
acTrans.Commit();
}
}

编辑多段线(.NET)

二维和三维多段线、矩形、多边形、圆环和三维多边形网格都是双曲面变体,并且以相同的方式进行编辑。

AutoCAD可识别拟合多段线和样条曲线拟合多段线。样条拟合使用曲线拟合,类似于B样条。样条曲线拟合多段线有两种:二次和三次。这两条多段线都由SPLINETYPE系统变量控制。拟合曲面使用标准曲线进行曲线拟合,并利用在任何给定顶点上设置的任何切线方向。

要编辑对象,请使用 Polyline 、 Polyline2d 或 Polyline3d 对象的属性和方法。使用以下属性和方法打开或关闭顶点、更改顶点的坐标或添加顶点:

Closed 属性

打开或闭合多段线

ConstantWidth 属性

设置多段线的恒定宽度。

AppendVertex 方法

将顶点添加到二维或三维多段线。

ReverseCurve

反转多段线的方向。

使用以下方法更新多段线的凸度或宽度:

SetBulgeAt

在给定分段索引的情况下,设置多段线的凸度。

SetStartWidthAt

在给定段索引的情况下,设置多段线的起始宽度。

Straighten

拉直二维或三维多段线。

编辑多段线

此示例创建一个多段线。然后,它将向第三段的顶点添加一个凸起,向第三段添加一个顶点,更改最后一段的宽度,最后闭合第三段。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
[CommandMethod("EditPolyline")]
public static void EditPolyline()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a lightweight polyline
using (Polyline acPoly = new Polyline())
{
acPoly.AddVertexAt(0, new Point2d(1, 1), 0, 0, 0);
acPoly.AddVertexAt(1, new Point2d(1, 2), 0, 0, 0);
acPoly.AddVertexAt(2, new Point2d(2, 2), 0, 0, 0);
acPoly.AddVertexAt(3, new Point2d(3, 2), 0, 0, 0);
acPoly.AddVertexAt(4, new Point2d(4, 4), 0, 0, 0);

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acPoly);
acTrans.AddNewlyCreatedDBObject(acPoly, true);

// Sets the bulge at index 3
acPoly.SetBulgeAt(3, -0.5);

// Add a new vertex
acPoly.AddVertexAt(5, new Point2d(4, 1), 0, 0, 0);

// Sets the start and end width at index 4
acPoly.SetStartWidthAt(4, 0.1);
acPoly.SetEndWidthAt(4, 0.5);

// Close the polyline
acPoly.Closed = true;
}

// Save the new objects to the database
acTrans.Commit();
}
}

编辑样条曲线(.NET)

可以编辑开放或闭合样条曲线的属性,甚至可以将其转换为曲线。使用以下特性可以打开或关闭样条曲线、更改其控制点或反转样条曲线的方向:

  • Degree

    返回样条曲线的多项式表示形式。

  • EndFitTangent

    返回样条线的端点切线作为方向向量。

  • FitTolerance

    使用新公差值将样条曲线重新拟合到现有点。

  • NumControlPoints

    返回样条曲线的控制点数。

  • NumFitPoints

    返回样条曲线的拟合点数。

  • StartFitTangent

    返回样条线的起始切线。

  • InsertFitPointAt

    在给定索引处向样条曲线添加单个拟合点。

  • ElevateDegree

    将样条曲线的阶数增加到给定的阶数。

  • GetControlPointAt

    获取给定索引处样条曲线的控制点。(Gets只有一个控制点)。 NumControlPoints 属性包含样条曲线的控制点数量。

  • GetFitPointAt

    获取给定索引处样条曲线的拟合点。(Gets仅一个拟合点。要查询样条曲线的所有拟合点,请使用 FitData 属性,然后查询使用其 GetFitPoints 成员函数返回的 FitData 对象。 NumFitPoints 属性包含样条曲线的拟合点数。

  • RemoveFitPointAt

    在给定索引处创建样条曲线的拟合点。

  • ReverseCurve

    反转样条曲线的方向。

  • SetControlPointAt

    在给定索引处设置样条曲线的控制点。

  • SetFitPointAt

    在给定索引处设置样条曲线的拟合点。(Sets仅一个拟合点。要更改样条曲线的所有拟合点,请使用 FitPoints 属性。)

  • SetWeightAt

    设置给定索引处控制点的权重。

使用以下只读属性查询样条曲线:

  • Area

    获取样条线的封闭区域。

  • Closed

    指示样条曲线是打开的还是闭合的。

  • Degree

    获取样条曲线的多项式表示形式的阶数。

  • IsPeriodic

    指定给定的样条曲线是否是周期性的。

  • IsPlanar

    指定给定样条曲线是否为平面样条曲线。

  • IsRational

    指定给定的样条曲线是否合理。

  • NumControlPoints

    获取样条曲线的控制点数目。

  • NumfFitPoints

    获取样条曲线的拟合点数。

更改样条曲线上的控制点

本示例创建样条曲线,然后更改样条曲线的第一个控制点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
[CommandMethod("EditSpline")]
public static void EditSpline()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a Point3d Collection
Point3dCollection acPt3dColl = new Point3dCollection();
acPt3dColl.Add(new Point3d(1, 1, 0));
acPt3dColl.Add(new Point3d(5, 5, 0));
acPt3dColl.Add(new Point3d(10, 0, 0));

// Set the start and end tangency
Vector3d acStartTan = new Vector3d(0.5, 0.5, 0);
Vector3d acEndTan = new Vector3d(0.5, 0.5, 0);

// Create a spline
using (Spline acSpline = new Spline(acPt3dColl,
acStartTan,
acEndTan, 4, 0))
{

// Set a control point
acSpline.SetControlPointAt(0, new Point3d(0, 3, 0));

// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acSpline);
acTrans.AddNewlyCreatedDBObject(acSpline, true);
}

// Save the new objects to the database
acTrans.Commit();
}
}

编辑图案填充(.NET)

可以编辑填充边界和填充图案。如果编辑关联图案填充的边界,则只要编辑产生有效边界,阵列就会更新。即使关联图案填充位于已关闭的图层上,它们也会更新。可以修改填充图案或为现有填充选择新图案,但只能在创建填充时设置关联性。可以使用 Associative 属性检查 Hatch 对象是否关联。

必须使用 EvaluateHatch 方法重新计算图案填充,才能查看对图案填充所做的任何编辑。

本节中的主题

  • 编辑填充边界 (.NET)
  • 编辑填充模式(.NET)

编辑填充边界 (.NET)

可以在 Hatch 对象的边界上附加、插入或删除循环。关联图案填充将更新以匹配对其边界所做的任何更改。不更新非关联图案填充。

要编辑图案填充边界,请使用以下方法之一:

  • AppendLoop

    将一个循环添加到图案填充。您定义了循环的类型,该类型附加了 AppendLoop 方法的第一个参数和由 HatchLoopTypes 枚举定义的常量。

  • GetLoopAt

    获取图案填充的给定索引处的循环。

  • InsertLoopAt

    在图案填充的给定索引处创建循环。

  • RemoveLoopAt

    在图案填充的给定索引处创建循环。

要查询图案填充边界,请使用以下方法之一:

  • LoopTypeAt

    获取图案填充的给定索引处的循环类型。

  • NumberOfLoops

    获取图案填充的循环数。

将内部循环附加到图案填充

本示例创建关联图案填充。然后创建一个圆,并将该圆作为内环附加到图案填充。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
[CommandMethod("EditHatchAppendLoop")]
public static void EditHatchAppendLoop()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create an arc object for the closed boundary to hatch
using (Arc acArc = new Arc(new Point3d(5, 3, 0), 3, 0, 3.141592))
{

acBlkTblRec.AppendEntity(acArc);
acTrans.AddNewlyCreatedDBObject(acArc, true);

// Create an line object for the closed boundary to hatch
using (Line acLine = new Line(acArc.StartPoint, acArc.EndPoint))
{
acBlkTblRec.AppendEntity(acLine);
acTrans.AddNewlyCreatedDBObject(acLine, true);

// Adds the arc and line to an object id collection
ObjectIdCollection acObjIdColl = new ObjectIdCollection();
acObjIdColl.Add(acArc.ObjectId);
acObjIdColl.Add(acLine.ObjectId);

// Create the hatch object and append it to the block table record
using (Hatch acHatch = new Hatch())
{
acBlkTblRec.AppendEntity(acHatch);
acTrans.AddNewlyCreatedDBObject(acHatch, true);

// Set the properties of the hatch object
// Associative must be set after the hatch object is appended to the
// block table record and before AppendLoop
acHatch.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31");
acHatch.Associative = true;
acHatch.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl);

// Create a circle object for the inner boundary of the hatch
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(5, 4.5, 0);
acCirc.Radius = 1;

acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);

// Adds the circle to an object id collection
acObjIdColl.Clear();
acObjIdColl.Add(acCirc.ObjectId);

// Append the circle as the inner loop of the hatch and evaluate it
acHatch.AppendLoop(HatchLoopTypes.Default, acObjIdColl);
acHatch.EvaluateHatch(true);
}
}
}
}

// Save the new object to the database
acTrans.Commit();
}
}

编辑填充模式 (.NET)

可以更改现有填充图案的角度或间距,也可以将其替换为实体填充、渐变填充或AutoCAD提供的预定义图案之一。“边界图案填充”对话框中的“图案”选项或功能区上的“图案”库将显示这些图案的列表。为了减小文件大小,图案填充在图形中定义为单个图形对象。

使用以下属性和方法编辑填充图案:

  • GradientAngle

    指定图案填充的渐变角度。

  • GradientName

    返回图案填充的渐变名称。

  • GradientShift

    指定图案填充的渐变移动。

  • GradientType

    返回图案填充的渐变类型。

  • PatternAngle

    指定填充图案的角度(弧度)。

  • PatternDouble

    指定用户定义的图案填充是否为双图案填充。

  • PatternName

    返回图案填充的填充图案名称。(Use用于设置填充图案名称和填充类型的 SetHatchPattern 方法。)

  • PatternScale

    指定填充图案比例。

  • PatternSpace

    指定用户定义的填充图案间距。

  • PatternType

    返回图案填充的填充图案类型。(Use用于设置填充图案名称和填充类型的 SetHatchPattern 方法。)

  • SetGradient

    设置图案填充的渐变类型和名称。

  • SetHatchPattern

    设置图案填充的图案类型和名称。

更改图案填充的图案间距

本示例创建图案填充。然后将图案填充的当前图案间距加2。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
[CommandMethod("EditHatchPatternScale")]
public static void EditHatchPatternScale()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle object for the boundary of the hatch
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(5, 3, 0);
acCirc.Radius = 3;

acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);

// Adds the arc and line to an object id collection
ObjectIdCollection acObjIdColl = new ObjectIdCollection();
acObjIdColl.Add(acCirc.ObjectId);

// Create the hatch object and append it to the block table record
using (Hatch acHatch = new Hatch())
{
acBlkTblRec.AppendEntity(acHatch);
acTrans.AddNewlyCreatedDBObject(acHatch, true);

// Set the properties of the hatch object
// Associative must be set after the hatch object is appended to the
// block table record and before AppendLoop
acHatch.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31");
acHatch.Associative = true;
acHatch.AppendLoop(HatchLoopTypes.Outermost, acObjIdColl);

// Evaluate the hatch
acHatch.EvaluateHatch(true);

// Increase the pattern scale by 2 and re-evaluate the hatch
acHatch.PatternScale = acHatch.PatternScale + 2;
acHatch.SetHatchPattern(acHatch.PatternType, acHatch.PatternName);
acHatch.EvaluateHatch(true);
}
}

// Save the new object to the database
acTrans.Commit();
}
}

使用图层、颜色和线型(.NET)

图层就像透明的覆盖层,您可以在其上组织和分组不同类型的图形信息。您创建的对象具有包括图层、颜色和线型在内的特性。颜色有助于区分图形中的相似元素,线型有助于轻松区分不同的绘图元素(如中心线或隐藏线)。组织图层和图层上的对象可以更轻松地管理图形中的信息。

本节中的主题

  • 使用图层(.NET)
  • 使用颜色(.NET)
  • 使用线型(.NET)

使用图层(.NET)

始终在图层上绘制。它可以是默认图层,也可以是您自己创建并命名的图层。每个图层都有关联的颜色和线型以及其他特性。例如,可以创建一个仅绘制中心线的图层,并将颜色和线型CENTER指定给该图层。然后,每当您想要绘制中心线时,您都可以切换到该层并开始绘制。

所有图层和线型都存储在单独的符号表中。图层保留在 LayerTable 中,线型保留在 LinetypeTable 中。

本节中的主题

  • 对图层和线型排序(.NET)
  • 创建和命名图层(.NET)
  • 将图层置为当前(.NET)
  • 打开和关闭图层(.NET)
  • 冻结和解冻图层(.NET)
  • 锁定和解锁层(.NET)
  • 为图层指定颜色(.NET)
  • 将线型指定给图层(.NET)
  • 擦除图层(.NET)

对图层和线型排序(.NET)

可以在“图层”和“线型”表中查找图形中的所有图层和线型。

遍历图层表

下面的代码循环访问Layers表以收集图形中所有图层的名称。然后,这些名称将显示在消息框中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[CommandMethod("DisplayLayerNames")]
public static void DisplayLayerNames()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

string sLayerNames = "";

foreach (ObjectId acObjId in acLyrTbl)
{
LayerTableRecord acLyrTblRec;
acLyrTblRec = acTrans.GetObject(acObjId,
OpenMode.ForRead) as LayerTableRecord;

sLayerNames = sLayerNames + "\n" + acLyrTblRec.Name;
}

Application.ShowAlertDialog("The layers in this drawing are: " +
sLayerNames);

// Dispose of the transaction
}
}

创建和命名图层(.NET)

可以创建新图层,并为这些图层指定颜色和线型特性。每个单独的层都是“层”(Layers)表格的一部分。使用 Add 函数创建一个新图层并将其添加到图层表中。

可以在创建图层时为其指定名称。若要在创建层后更改其名称,请使用 Name 特性。图层名称最多可包含255个字符,并包含字母、数字和特殊字符美元符号($)、连字符(-)和下划线(_)。

创建一个新图层,将其指定为绿色,然后向图层中添加一个对象

下面的代码创建一个新的层和圆对象。新图层被指定为绿色。将圆指定给图层,圆的颜色将相应地更改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
[CommandMethod("CreateAndAssignALayer")]
public static void CreateAndAssignALayer()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

string sLayerName = "Center";

if (acLyrTbl.Has(sLayerName) == false)
{
using (LayerTableRecord acLyrTblRec = new LayerTableRecord())
{
// Assign the layer the ACI color 3 and a name
acLyrTblRec.Color = Color.FromColorIndex(ColorMethod.ByAci, 3);
acLyrTblRec.Name = sLayerName;

// Upgrade the Layer table for write
acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite);

// Append the new layer to the Layer table and the transaction
acLyrTbl.Add(acLyrTblRec);
acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
}
}

// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle object
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(2, 2, 0);
acCirc.Radius = 1;
acCirc.Layer = sLayerName;

acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

将图层置为当前(.NET)

您始终在活动层上绘制。激活某个层时,将在该层上创建新对象。如果激活其他图层,则会为创建的任何新对象指定该新的激活图层,并使用其颜色和线型。如果图层处于冻结状态,则无法激活该图层。

要激活图层,请使用 Database 对象的 Clayer 特性或CLAYER系统变量。举例来说:

使图层成为数据库中的当前图层

此示例通过具有 Clayer 属性的 Database 对象设置当前图层。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[CommandMethod("SetLayerCurrent")]
public static void SetLayerCurrent()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

string sLayerName = "Center";

if (acLyrTbl.Has(sLayerName) == true)
{
// Set the layer Center current
acCurDb.Clayer = acLyrTbl[sLayerName];

// Save the changes
acTrans.Commit();
}

// Dispose of the transaction
}
}

使用CLAYER系统变量将图层置为当前图层

此示例使用CLAYER系统变量将图层设置为当前图层。

1
Application.SetSystemVariable("CLAYER", "Center");

打开和关闭图层(.NET)

关闭的图层将与图形一起重新生成,但不会显示或打印。通过关闭图层,可以避免每次解冻图层时重新生成图形。打开已关闭的图层时,AutoCAD将在该图层上重绘对象。

对表示要打开或关闭的图层的 LayerTableRecord 对象使用 IsOff 特性。如果输入值 TRUE ,则图层将关闭。如果输入值 FALSE ,则图层将启用。

关闭图层

此示例创建一个新层并将其关闭,然后向该层添加一个圆,使该圆不再可见。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
[CommandMethod("TurnLayerOff")]
public static void TurnLayerOff()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

string sLayerName = "ABC";

if (acLyrTbl.Has(sLayerName) == false)
{
using (LayerTableRecord acLyrTblRec = new LayerTableRecord())
{
// Assign the layer a name
acLyrTblRec.Name = sLayerName;

// Turn the layer off
acLyrTblRec.IsOff = true;

// Upgrade the Layer table for write
acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite);

// Append the new layer to the Layer table and the transaction
acLyrTbl.Add(acLyrTblRec);
acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
}
}
else
{
LayerTableRecord acLyrTblRec = acTrans.GetObject(acLyrTbl[sLayerName],
OpenMode.ForWrite) as LayerTableRecord;

// Turn the layer off
acLyrTblRec.IsOff = true;
}

// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle object
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(2, 2, 0);
acCirc.Radius = 1;
acCirc.Layer = sLayerName;

acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

冻结和解冻图层(.NET)

可以冻结图层以加快显示更改、提高对象选择性能并减少复杂图形的再生时间。AutoCAD不会显示、打印或重新生成冻结图层上的对象。冻结长时间不使用的图层。当您“解冻”冻结的图层时,AutoCAD会重新生成并显示该图层上的对象。

使用 IsFrozen 特性冻结或解冻图层。如果输入值 TRUE ,则图层将被冻结。如果输入值 FALSE ,则解冻图层。

冻结图层

此示例创建一个名为“ABC”的新层,然后冻结该层。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
[CommandMethod("FreezeLayer")]
public static void FreezeLayer()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

string sLayerName = "ABC";

if (acLyrTbl.Has(sLayerName) == false)
{
using (LayerTableRecord acLyrTblRec = new LayerTableRecord())
{
// Assign the layer a name
acLyrTblRec.Name = sLayerName;

// Freeze the layer
acLyrTblRec.IsFrozen = true;

// Upgrade the Layer table for write
acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite);

// Append the new layer to the Layer table and the transaction
acLyrTbl.Add(acLyrTblRec);
acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
}
}
else
{
LayerTableRecord acLyrTblRec = acTrans.GetObject(acLyrTbl[sLayerName],
OpenMode.ForWrite) as LayerTableRecord;

// Freeze the layer
acLyrTblRec.IsFrozen = true;
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

锁定和解锁层(.NET)

无法编辑锁定图层上的对象;但是,如果图层打开并解冻,则这些对象仍然可见。您可以将锁定的图层置为当前图层,并向其添加对象。您可以冻结和关闭锁定的图层,并更改其关联的颜色和线型。

使用 IsLocked 特性锁定或解锁图层。如果输入值 TRUE ,则图层将被锁定。如果输入值 FALSE ,则图层将被解锁。

此示例创建一个名为“ABC”的新层,然后锁定该层。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
[CommandMethod("LockLayer")]
public static void LockLayer()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

string sLayerName = "ABC";

if (acLyrTbl.Has(sLayerName) == false)
{
using (LayerTableRecord acLyrTblRec = new LayerTableRecord())
{
// Assign the layer a name
acLyrTblRec.Name = sLayerName;

// Lock the layer
acLyrTblRec.IsLocked = true;

// Upgrade the Layer table for write
acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite);

// Append the new layer to the Layer table and the transaction
acLyrTbl.Add(acLyrTblRec);
acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
}
}
else
{
LayerTableRecord acLyrTblRec = acTrans.GetObject(acLyrTbl[sLayerName],
OpenMode.ForWrite) as LayerTableRecord;

// Lock the layer
acLyrTblRec.IsLocked = true;
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

为图层指定颜色(.NET)

每一层都可以有自己的颜色。层的颜色由Color对象标识,该对象是Colors命名空间的一部分。该对象可以保存RGB值、ACI编号(1到255之间的整数)或配色系统颜色。

要为图层指定颜色,请使用 Color 特性。

注意:像直线和圆这样的对象支持两种不同的属性来控制它们的当前颜色。 Color 属性用于指定RGB值、ACI编号或配色系统颜色,而 ColorIndex 属性仅支持ACI编号。

如果使用ACI颜色0或“ByBlock”,AutoCAD将以默认颜色(白色或黑色,具体取决于配置)绘制新对象,直到将它们编组到块中。插入块后,块中的对象将继承当前特性设置。

如果使用ACI颜色256或ByLayer,则新对象将继承在其上绘制它们的图层的颜色。

设置图层的颜色

下面的示例创建三个新图层,并使用三种颜色方法中的每一种为每个图层指定不同的颜色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
[CommandMethod("SetLayerColor")]
public static void SetLayerColor()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

// Define an array of layer names
string[] sLayerNames = new string[3];
sLayerNames[0] = "ACIRed";
sLayerNames[1] = "TrueBlue";
sLayerNames[2] = "ColorBookYellow";

// Define an array of colors for the layers
Color[] acColors = new Color[3];
acColors[0] = Color.FromColorIndex(ColorMethod.ByAci, 1);
acColors[1] = Color.FromRgb(23, 54, 232);
acColors[2] = Color.FromNames("PANTONE Yellow 0131 C",
"PANTONE+ Pastels & Neons Coated");

int nCnt = 0;

// Add or change each layer in the drawing
foreach (string sLayerName in sLayerNames)
{
if (acLyrTbl.Has(sLayerName) == false)
{
using (LayerTableRecord acLyrTblRec = new LayerTableRecord())
{
// Assign the layer a name
acLyrTblRec.Name = sLayerName;

// Set the color of the layer
acLyrTblRec.Color = acColors[nCnt];

// Upgrade the Layer table for write
if (acLyrTbl.IsWriteEnabled == false) acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite);

// Append the new layer to the Layer table and the transaction
acLyrTbl.Add(acLyrTblRec);
acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
}
}
else
{
// Open the layer if it already exists for write
LayerTableRecord acLyrTblRec = acTrans.GetObject(acLyrTbl[sLayerName],
OpenMode.ForWrite) as LayerTableRecord;

// Set the color of the layer
acLyrTblRec.Color = acColors[nCnt];
}

nCnt = nCnt + 1;
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

将线型指定给图层(.NET)

定义图层时,线型提供了另一种表达视觉信息的方式。线型是由短划线、点和空格组成的重复图案,可用于区分不同线条的用途。

线型名称和定义描述了特定的点划线序列、破折号和空格的相对长度以及任何包含的文字或形状的特征。

使用线型特性可以将线型指定给图层。此属性将线型的名称作为输入。

注意:必须先在图形中定义线型,然后才能将线型指定给图层。

设置图层的线型

下面的示例创建一个名为“ABC”的新图层,并为其指定“Center”线型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
[CommandMethod("SetLayerLinetype")]
public static void SetLayerLinetype()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

string sLayerName = "ABC";

if (acLyrTbl.Has(sLayerName) == false)
{
using (LayerTableRecord acLyrTblRec = new LayerTableRecord())
{
// Assign the layer a name
acLyrTblRec.Name = sLayerName;

// Open the Layer table for read
LinetypeTable acLinTbl;
acLinTbl = acTrans.GetObject(acCurDb.LinetypeTableId,
OpenMode.ForRead) as LinetypeTable;

if (acLinTbl.Has("Center") == true)
{
// Set the linetype for the layer
acLyrTblRec.LinetypeObjectId = acLinTbl["Center"];
}

// Upgrade the Layer table for write
acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForWrite);

// Append the new layer to the Layer table and the transaction
acLyrTbl.Add(acLyrTblRec);
acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
}
}
else
{
LayerTableRecord acLyrTblRec = acTrans.GetObject(acLyrTbl[sLayerName],
OpenMode.ForRead) as LayerTableRecord;

// Open the Layer table for read
LinetypeTable acLinTbl;
acLinTbl = acTrans.GetObject(acCurDb.LinetypeTableId,
OpenMode.ForRead) as LinetypeTable;

if (acLinTbl.Has("Center") == true)
{
// Upgrade the Layer Table Record for write
acTrans.GetObject(acLyrTbl[sLayerName], OpenMode.ForWrite);

// Set the linetype for the layer
acLyrTblRec.LinetypeObjectId = acLinTbl["Center"];
}
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

擦除图层(.NET)

可以在绘图任务期间随时删除图层。不能删除当前图层、图层0、依赖外部参照的图层或包含对象的图层。

要擦除图层,请使用 Erase 方法。建议使用清除功能来验证是否可以清除层,沿着验证它是否不是层0、Defpoints或当前层。

注意:块定义所参照的图层以及名为DEFPOINTS的特殊图层沿着不能删除,即使它们不包含可见对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
[CommandMethod("EraseLayer")]
public static void EraseLayer()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Layer table for read
LayerTable acLyrTbl;
acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
OpenMode.ForRead) as LayerTable;

string sLayerName = "ABC";

if (acLyrTbl.Has(sLayerName) == true)
{
// Check to see if it is safe to erase layer
ObjectIdCollection acObjIdColl = new ObjectIdCollection();
acObjIdColl.Add(acLyrTbl[sLayerName]);
acCurDb.Purge(acObjIdColl);

if (acObjIdColl.Count > 0)
{
LayerTableRecord acLyrTblRec;
acLyrTblRec = acTrans.GetObject(acObjIdColl[0],
OpenMode.ForWrite) as LayerTableRecord;

try
{
// Erase the unreferenced layer
acLyrTblRec.Erase(true);

// Save the changes and dispose of the transaction
acTrans.Commit();
}
catch (Autodesk.AutoCAD.Runtime.Exception Ex)
{
// Layer could not be deleted
Application.ShowAlertDialog("Error:\n" + Ex.Message);
}
}
}
}
}

使用颜色(.NET)

使用图形中单个对象的 Color 或 ColorIndex 特性为其指定颜色。 ColorIndex 特性接受AutoCAD颜色索引(ACI)值作为0 - 256的数值。 Color 属性用于为对象指定ACI编号、真彩色或配色系统颜色。要更改 Color 属性的值,可以使用 Colors 命名空间下的 Color 对象。

Color 对象有 SetRGB 方法,允许您根据将红色、绿色和蓝色值混合在一起从数百万种颜色组合中进行选择。 Color 对象还包含用于指定颜色名称、配色系统、颜色索引和颜色值的方法和属性。

也可以为图层指定颜色。如果希望对象继承其所在图层的颜色,请通过将其ACI值设置为256,将对象的颜色设置为ByLayer。任何数量的对象和图层都可以具有相同的颜色编号。您可以将每种颜色编号指定给画笔上的不同画笔,或者使用颜色编号来标识图形中的某些对象,即使您在屏幕上看不到颜色。

本节中的主题

  • 为对象指定颜色值(.NET)
  • 通过数据库使颜色成为当前颜色(.NET)
  • 使用CECOLOR系统变量(.NET)设置当前颜色

为对象指定颜色值(.NET)

下面的示例创建四个圆,并使用四种不同的方法为每个圆指定不同的颜色。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
[CommandMethod("SetObjectColor")]
public static void SetObjectColor()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Define an array of colors for the layers
Color[] acColors = new Color[3];
acColors[0] = Color.FromColorIndex(ColorMethod.ByAci, 1);
acColors[1] = Color.FromRgb(23, 54, 232);
acColors[2] = Color.FromNames("PANTONE Yellow 0131 C",
"PANTONE(R) pastel coated");

// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle object and assign it the ACI value of 4
Point3d acPt = new Point3d(0, 3, 0);
using (Circle acCirc = new Circle())
{
acCirc.Center = acPt;
acCirc.Radius = 1;
acCirc.ColorIndex = 4;

acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);

int nCnt = 0;

while (nCnt < 3)
{
// Create a copy of the circle
Circle acCircCopy;
acCircCopy = acCirc.Clone() as Circle;

// Shift the copy along the Y-axis
acPt = new Point3d(acPt.X, acPt.Y + 3, acPt.Z);
acCircCopy.Center = acPt;

// Assign the new color to the circle
acCircCopy.Color = acColors[nCnt];

acBlkTblRec.AppendEntity(acCircCopy);
acTrans.AddNewlyCreatedDBObject(acCircCopy, true);

nCnt = nCnt + 1;
}
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

通过数据库使颜色成为当前颜色(.NET)

此示例通过具有 Cecolor 属性的 Database 对象设置当前颜色。

1
2
3
4
5
6
7
8
9
[CommandMethod("SetColorCurrent")]
public static void SetColorCurrent()
{
// Get the current document
Document acDoc = Application.DocumentManager.MdiActiveDocument;

// Set the current color
acDoc.Database.Cecolor = Color.FromColorIndex(ColorMethod.ByLayer, 256);
}

使用CECOLOR系统变量(.NET)设置当前颜色

此示例使用CECOLOR系统变量设置当前红色。

1
Application.SetSystemVariable("CECOLOR", "1");

使用线型(.NET)

线型是由短划线、点和空格组成的重复图案。复杂线型是符号的重复图案。要使用线型,必须首先将其加载到图形中。在将线型加载到图形中之前,LIN库文件中必须存在线型定义。要将线型加载到图形中,请使用 Database 对象的成员方法 LoadLineTypeFile 。

注意:AutoCAD内部使用的线型不应与某些绘图仪提供的硬件线型混淆。两种类型的虚线产生类似的结果。但是,不要同时使用这两种类型,因为结果可能无法预测。

将线型加载到AutoCAD

本示例尝试从acad.lin文件加载线型“CENTER”。如果线型已存在或文件不存在,则会显示一条消息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[CommandMethod("LoadLinetype")]
public static void LoadLinetype()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Linetype table for read
LinetypeTable acLineTypTbl;
acLineTypTbl = acTrans.GetObject(acCurDb.LinetypeTableId,
OpenMode.ForRead) as LinetypeTable;

string sLineTypName = "Center";

if (acLineTypTbl.Has(sLineTypName) == false)
{
// Load the Center Linetype
acCurDb.LoadLineTypeFile(sLineTypName, "acad.lin");
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

本节中的主题

  • 激活线型(.NET)
  • 重命名线型(.NET)
  • 删除线型(.NET)
  • 更改线型说明(.NET)
  • 指定线型比例(.NET)

激活线型(.NET)

要使用线型,必须将其激活。所有新创建的对象都将使用活动线型绘制。将线型应用于对象有两种不同的方法:直接或继承。您可以直接将线型指定给对象,该对象将覆盖指定给对象所在图层的线型。否则,对象将通过将其 Linetype 或 LinetypeId 属性设置为表示ByLayer线型来继承其所在图层的线型。

注意:不能激活依赖于外部参照的线型。

每个图形中都有三种线型:BYBLOCK、BYLAYER和CONTINUOUS。可以从Linetype表对象或使用 SymbolUtilityServices 对象中的方法访问这些线型中的每一种。使用以下方法可以获取这些默认线型的对象ID:

  • GetLinetypeByBlockId-返回BYBLOCK线型的对象ID。
  • GetLinetypeByLayerId-返回BYLAYER线型的对象ID。
  • GetLinetypeContinuousId-返回CONTINUOUS线型的对象ID。
将线型指定给对象(.NET)

下面的示例创建一个圆并为其指定“Center”线型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
[CommandMethod("SetObjectLinetype")]
public static void SetObjectLinetype()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Linetype table for read
LinetypeTable acLineTypTbl;
acLineTypTbl = acTrans.GetObject(acCurDb.LinetypeTableId,
OpenMode.ForRead) as LinetypeTable;

string sLineTypName = "Center";

if (acLineTypTbl.Has(sLineTypName) == false)
{
acCurDb.LoadLineTypeFile(sLineTypName, "acad.lin");
}

// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle object
using (Circle acCirc = new Circle())
{
acCirc.Center = new Point3d(2, 2, 0);
acCirc.Radius = 1;
acCirc.Linetype = sLineTypName;

acBlkTblRec.AppendEntity(acCirc);
acTrans.AddNewlyCreatedDBObject(acCirc, true);
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}
通过数据库使线型成为当前线型(.NET)

此示例使用 Celtype 特性将线型设置为当前通过 Database 对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[CommandMethod("SetLinetypeCurrent")]
public static void SetLinetypeCurrent()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Linetype table for read
LinetypeTable acLineTypTbl;
acLineTypTbl = acTrans.GetObject(acCurDb.LinetypeTableId,
OpenMode.ForRead) as LinetypeTable;

string sLineTypName = "Center";

if (acLineTypTbl.Has(sLineTypName) == true)
{
// Set the linetype Center current
acCurDb.Celtype = acLineTypTbl[sLineTypName];

// Save the changes
acTrans.Commit();
}

// Dispose of the transaction
}
}
使用CELTYPE系统变量(.NET)使线型成为当前线型

此示例使用CELTYPE系统变量设置线型的当前值。

1
Application.SetSystemVariable("CELTYPE", "Center");

重命名线型(.NET)

要重命名线型,请使用 Name 特性。重命名线型时,仅重命名图形中的线型定义。LIN库文件中的名称不会更新以反映新名称。

删除线型(.NET)

要删除线型,请使用 Erase 方法。可以在绘图任务期间随时删除线型;但是,不能删除的线型包括BYLAYER、BYBLOCK、CONTINUOUS、当前线型、正在使用的线型和依赖外部参照的线型。此外,不能删除由块定义参照的线型,即使这些线型未被任何对象使用。

更改线型说明(.NET)

线型可以具有与其关联的说明。说明提供了线型的ASCII表示形式。可以使用 AsciiDescription 特性指定或修改线型描述。

线型说明最多可包含47个字符。说明可以是注释或一系列下划线、点、破折号和空格,以显示线型图案的简单表示。

更改线型的描述

下面的示例更改当前线型的说明。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[CommandMethod("ChangeLinetypeDescription")]
public static void ChangeLinetypeDescription()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Linetype table record of the current linetype for write
LinetypeTableRecord acLineTypTblRec;
acLineTypTblRec = acTrans.GetObject(acCurDb.Celtype,
OpenMode.ForWrite) as LinetypeTableRecord;

// Change the description of the current linetype
acLineTypTblRec.AsciiDescription = "Exterior Wall";

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

指定线型比例(.NET)

可以为创建的对象指定线型比例。比例越小,每个绘图单元生成的图案重复次数越多。默认情况下,AutoCAD使用的全局线型比例为1.0,等于一个图形单位。可以更改所有图形对象和属性参照的线型比例。

CELTSCALE系统变量可为新创建的对象设置线型比例。LTSCALE系统变量可更改现有对象和新对象的全局线型比例。对象的 LinetypeScale 特性用于更改对象的线型比例。对象显示时的线型比例基于单个对象的线型比例乘以全局线型比例。

更改对象的线型比例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
[CommandMethod("SetObjectLinetypeScale")]
public static void SetObjectLinetypeScale()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Save the current linetype
ObjectId acObjId = acCurDb.Celtype;

// Set the global linetype scale
acCurDb.Ltscale = 3;

// Open the Linetype table for read
LinetypeTable acLineTypTbl;
acLineTypTbl = acTrans.GetObject(acCurDb.LinetypeTableId,
OpenMode.ForRead) as LinetypeTable;

string sLineTypName = "Border";

if (acLineTypTbl.Has(sLineTypName) == false)
{
acCurDb.LoadLineTypeFile(sLineTypName, "acad.lin");
}

// Set the Border linetype current
acCurDb.Celtype = acLineTypTbl[sLineTypName];

// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a circle object and set its linetype
// scale to half of full size
using (Circle acCirc1 = new Circle())
{
acCirc1.Center = new Point3d(2, 2, 0);
acCirc1.Radius = 4;
acCirc1.LinetypeScale = 0.5;

acBlkTblRec.AppendEntity(acCirc1);
acTrans.AddNewlyCreatedDBObject(acCirc1, true);

// Create a second circle object
using (Circle acCirc2 = new Circle())
{
acCirc2.Center = new Point3d(12, 2, 0);
acCirc2.Radius = 4;

acBlkTblRec.AppendEntity(acCirc2);
acTrans.AddNewlyCreatedDBObject(acCirc2, true);
}
}

// Restore the original active linetype
acCurDb.Celtype = acObjId;

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

保存和恢复图层状态(.NET)

可以将图层状态保存在图形中,以后再恢复它们。这样,在完成图形或打印图形时,可以在不同阶段轻松返回所有图层的指定设置。

图层状态包括图层是否在新视口中打开、冻结、锁定、打印和自动冻结,以及图层的颜色、线型、线宽和打印样式。可以指定要保存的设置,也可以为图形保存不同的设置组。

LayerStateManager 用于保存和恢复图层状态。

本节中的主题

  • 了解AutoCAD图层的状态(.NET)
  • 使用LayerStateManager管理图层状态(.NET)

了解AutoCAD图层的状态(.NET)

AutoCAD将图层设置信息保存在 LayerTable 对象的扩展字典中。第一次保存图层状态时,AutoCAD将执行以下操作:

  • 在“层”(Layers)表格上创建扩展字典。
  • 在扩展字典中创建名为ACAD_LAYERSTATE的 Dictionary 对象。
  • 将图形中每个图层的特性存储在ACAD_LAYERSTATE字典的 XRecord 对象中。AutoCAD将所有图层设置存储在 XRecord 中,但会标识您选择保存的特定设置。恢复图层设置时,AutoCAD仅恢复选择保存的设置。

每次在图形中保存另一个图层设置时,AutoCAD都会创建另一个描述已保存设置的 XRecord 对象,并将 XRecord 存储在ACAD_LAYERSTATE字典中。下图说明了该过程。

在处理图层状态时,不需要(也不应尝试)直接操作条目。使用 LayerStateManager 对象的函数访问字典。一旦您引用了字典,您就可以逐步浏览表示为 DBDictionaryEntry 对象的每个条目。

列出图形中保存的图层状态

如果图层状态已保存在当前图形中,以下代码将列出所有已保存图层状态的名称:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
[CommandMethod("ListLayerStates")]
public static void ListLayerStates()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
LayerStateManager acLyrStMan;
acLyrStMan = acCurDb.LayerStateManager;

DBDictionary acDbDict;
acDbDict = acTrans.GetObject(acLyrStMan.LayerStatesDictionaryId(true),
OpenMode.ForRead) as DBDictionary;

string sLayerStateNames = "";

foreach (DBDictionaryEntry acDbDictEnt in acDbDict)
{
sLayerStateNames = sLayerStateNames + "\n" + acDbDictEnt.Key;
}

Application.ShowAlertDialog("The saved layer settings in this drawing are:" +
sLayerStateNames);

// Dispose of the transaction
}
}

使用LayerStateManager管理图层状态(.NET)

LayerStateManager 对象提供了一组用于创建和操作保存的图层状态的函数。使用以下 LayerStateManager 函数处理图层状态:

  • DeleteLayerState

    删除保存的图层状态。

  • ExportLayerState

    将指定的已保存图层状态导出到LAS文件。

  • ImportLayerState

    从指定的LAS文件导入图层状态。

  • ImportLayerStateFromDb

    从其他数据库导入图层状态。

  • RenameLayerState

    重命名保存的图层状态。

  • RestoreLayerState

    恢复当前图形中的指定图层状态。

  • SaveLayerState

    重新定义指定的图层状态及其属性。

数据库的 LayerStateManager 对象可以通过使用 Database 对象的 LayerManagerState 属性来访问。

1
2
3
4
5
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

LayerStateManager acLyrStMan;
acLyrStMan = acCurDb.LayerStateManager;

本节中的主题

  • 保存图层状态(.NET)
  • 重命名图层状态(.NET)
  • 删除图层状态(.NET)
  • 还原图层状态(.NET)
  • 导出和导入保存的层状态(.NET)

保存图层状态(.NET)

使用 SaveLayerState 方法保存图形中的一组图层设置。 SaveLayerState 方法需要三个参数。第一个参数是命名要保存的图层状态的字符串。第二个参数标识要保存的图层特性。使用 LayerStateMasks 枚举的常量标识要保存的图层设置。下表列出了作为 LayerStateMasks 枚举一部分的常量。

图层状态掩码的属性

Constant name Layer property
Color Color
CurrentViewport Current viewport layers frozen or thawed
Frozen Frozen or thawed
LastRestored Last restored layer
LineType Linetype
LineWeight Lineweight
Locked Locked or unlocked
NewViewport New viewport layers frozen or thawed
None No layer settings
On On or off
Plot Plotting on or off
PlotStyle Plot style

将这些常数相加以指定多个属性。

第三个必需的参数是要保存其层设置的视口的对象ID。使用 ObjectId.Null 不指定视口。如果尝试以已存在的名称保存图层状态,将返回错误。必须先重命名或删除现有图层状态,然后才能重新使用该名称。

保存图层的颜色和线型设置

下面的代码将图形中当前图层的颜色和线型设置保存为ColorLinetype。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[CommandMethod("SaveLayerColorAndLinetype")]
public static void SaveLayerColorAndLinetype()
{
// Get the current document
Document acDoc = Application.DocumentManager.MdiActiveDocument;

LayerStateManager acLyrStMan;
acLyrStMan = acDoc.Database.LayerStateManager;

string sLyrStName = "ColorLinetype";

if (acLyrStMan.HasLayerState(sLyrStName) == false)
{
acLyrStMan.SaveLayerState(sLyrStName,
LayerStateMasks.Color |
LayerStateMasks.LineType,
ObjectId.Null);
}
}

重命名图层状态(.NET)

RenameLayerState 方法将图形中保存的图层状态从一个名称重命名为另一个名称。下面的代码将ColorLinetype图层设置重命名为OldColorLinetype。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[CommandMethod("RenameLayerState")]
public static void RenameLayerState()
{
// Get the current document
Document acDoc = Application.DocumentManager.MdiActiveDocument;

LayerStateManager acLyrStMan;
acLyrStMan = acDoc.Database.LayerStateManager;

string sLyrStName = "ColorLinetype";
string sLyrStNewName = "OldColorLinetype";

if (acLyrStMan.HasLayerState(sLyrStName) == true &&
acLyrStMan.HasLayerState(sLyrStNewName) == false)
{
acLyrStMan.RenameLayerState(sLyrStName, sLyrStNewName);
}
}

删除图层状态(.NET)

DeleteLayerState 方法从图形中删除保存的图层状态。下面的代码删除以ColorLinetype名称保存的图层状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[CommandMethod("RemoveLayerState")]
public static void RemoveLayerState()
{
// Get the current document
Document acDoc = Application.DocumentManager.MdiActiveDocument;

LayerStateManager acLyrStMan;
acLyrStMan = acDoc.Database.LayerStateManager;

string sLyrStName = "ColorLinetype";

if (acLyrStMan.HasLayerState(sLyrStName) == true)
{
acLyrStMan.DeleteLayerState(sLyrStName);
}
}

还原图层状态(.NET)

RestoreLayerState 方法重置图层状态中的图层设置,需要四个值。第一个值是要恢复的图层状态的名称,第二个值是要恢复其图层设置的视口的对象ID。第三个值是一个整数,它定义如何处理不在层状态中的层。第四个值确定要恢复的图层设置。

以下值确定如何处理未处于图层状态的图层:

  • 0 - 不处于图层状态的图层保持不变
  • 1 - 关闭不在图层状态的图层
  • 2 - 不在图层状态的图层在当前视口中冻结
  • 4 - 图层设置恢复为视口覆盖

注意:您可以使用前面列出的多个值的总和来定义未处于图层状态的图层的恢复行为。例如,可以关闭并冻结未与图层状态一起保存的图层。

例如,如果将颜色和线型设置保存在名称“ColorLinetype”下,然后更改这些设置,则恢复“ColorLinetype”会将图层重置为保存“ColorLinetype”时的颜色和线型。如果在保存“ColorLinetype”后向图形中添加新图层,则在恢复“ColorLinetype”时,这些新图层不会受到影响。

恢复图形图层的颜色和线型设置

假设当前图形中图层的颜色和线型设置以前以“ColorLinetype”的名称保存,则以下代码会将图形中每个图层的颜色和线型设置恢复为保存“ColorLinetype”时的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[CommandMethod("RestoreLayerState")]
public static void RestoreLayerState()
{
// Get the current document
Document acDoc = Application.DocumentManager.MdiActiveDocument;

LayerStateManager acLyrStMan;
acLyrStMan = acDoc.Database.LayerStateManager;

string sLyrStName = "ColorLinetype";

if (acLyrStMan.HasLayerState(sLyrStName) == true)
{
acLyrStMan.RestoreLayerState(sLyrStName,
ObjectId.Null,
1,
LayerStateMasks.Color |
LayerStateMasks.LineType);
}
}

导出和导入保存的层状态(.NET)

可以输出和输入保存的图层状态,以便在其他图形中使用相同的图层设置。使用 ExportLayerState 方法将保存的图层状态输出到LAS文件;使用 ImportLayerState 方法将LAS文件输入到图形。

注意:删除图层状态不会恢复它们;导入图层状态后,必须使用 RestoreLayerState 方法恢复图层状态。

ExportLayerState 方法接受两个参数。第一个参数是标识要导出的已保存图层状态的字符串。第二个参数是要将图层状态导出到的文件的名称。如果未指定文件的路径,则该文件将保存在打开图形的同一目录中。如果指定的文件名已存在,则覆盖现有文件。使用.命名文件时使用las扩展名;这是AutoCAD为导出的图层状态文件识别的扩展名。

ImportLayerState 方法接受一个参数:一个字符串,用于命名包含要导入的图层状态的文件。如果要输入的图层状态不在LAS文件中,而在图形文件中。可以打开图形文件,然后使用 ImportLayerStateFromDb 方法从其他图形的Database对象导入图层状态。

输入图层状态时,如果保存的设置中引用的任何特性在要输入到的图形中不可用,则会引发错误条件。但是,导入已完成,并使用默认属性。例如,如果将导出的图层设置为未加载到要导入该图层的图形中的线型,则会引发错误条件,并替换图形的默认线型。您的代码应考虑此错误情况,并在引发此错误时继续处理。

如果输入的文件为当前图形中不存在的图层定义了设置,则将在当前图形中创建这些图层。使用 RestoreLayerState 方法时,保存设置时指定的特性将指定给新图层;新图层的所有其他特性将指定为默认设置。

导出保存的图层设置

下面的示例将保存的图层状态导出到名为ColorLinetype.las的文件中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[CommandMethod("ExportLayerState")]
public static void ExportLayerState()
{
// Get the current document
Document acDoc = Application.DocumentManager.MdiActiveDocument;

LayerStateManager acLyrStMan;
acLyrStMan = acDoc.Database.LayerStateManager;

string sLyrStName = "ColorLinetype";

if (acLyrStMan.HasLayerState(sLyrStName) == true)
{
acLyrStMan.ExportLayerState(sLyrStName, "c:\\my documents\\" +
sLyrStName + ".las");
}
}

导入保存的图层设置

下面的示例从名为ColorLinetype.las的文件导入图层状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[CommandMethod("ImportLayerState")]
public static void ImportLayerState()
{
// Get the current document
Document acDoc = Application.DocumentManager.MdiActiveDocument;

LayerStateManager acLyrStMan;
acLyrStMan = acDoc.Database.LayerStateManager;

string sLyrStFileName = "c:\\my documents\\ColorLinetype.las";

if (System.IO.File.Exists(sLyrStFileName))
{
try
{
acLyrStMan.ImportLayerState(sLyrStFileName);
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
Application.ShowAlertDialog(ex.Message);
}
}
}

将文本添加到图形(.NET)

文字传达图形中的重要信息。将文字对象用于标题栏、标记工程图的各个部分、给出规格或进行注释。

AutoCAD提供了多种创建文字的方法。对于简短的条目,请使用单行文本。对于具有内部格式的较长条目,请使用多行文本( MText )。尽管所有输入的文本都使用当前文本样式(该样式用于建立默认字体和格式设置),但您可以使用多种方法自定义文本外观。

本节中的主题

  • 使用多行文本(.NET)
  • 使用单行文字(.NET)
  • 使用文本样式(.NET)
  • 使用Unicode字符、控制代码和特殊字符(.NET)
  • 拼写检查(.NET)

使用多行文本(.NET)

对于较长的复杂条目,请创建多行文本( MText )。多行文字适合指定的宽度,但可以垂直延伸到任意长度。您可以在 MText.

本节中的主题

  • 创建多行文本(.NET)
  • 设置多行文字格式(.NET)

创建多行文本(.NET)

先创建 MText 对象的实例,然后将其添加到表示模型或图纸空间的块表记录中,可以创建多行文字对象。 MText 对象构造函数不带任何参数。创建 MText 对象的实例后,可以使用其属性为其分配文本字符串、插入点和宽度等值。您可以更改的其他属性会影响对象的文字高度、对正、旋转角度和文字样式,或将字符格式应用于选定字符

创建多行文字对象

以下示例在模型空间中的坐标(2,2,0)处创建一个 MText 对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
[CommandMethod("CreateMText")]
public static void CreateMText()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a multiline text object
using (MText acMText = new MText())
{
acMText.Location = new Point3d(2, 2, 0);
acMText.Width = 4;
acMText.Contents = "This is a text string for the MText object.";

acBlkTblRec.AppendEntity(acMText);
acTrans.AddNewlyCreatedDBObject(acMText, true);
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

设置多行文字格式(.NET)

新创建的多行文字将自动采用当前文字样式的特征。默认文字样式为STANDARD。通过将格式应用于单个字符并将特性应用于多行文字对象,可以替代默认文字样式。您还可以使用本节中描述的方法指示格式或特殊字符。

方向选项(如样式、对正、宽度和旋转)影响多行文字边界内的所有文字,而不影响特定的单词或字符。使用 Attachment 特性可以更改多行文字对象的对齐方式,使用 Rotation 特性可以控制旋转角度。

TextStyleId 属性设置多行文字对象的字体和格式特征。创建多行文字时,可以从现有样式列表中选择要使用的样式。如果多行文字对象的任何部分都应用了字符格式,则更改该多行文字对象的样式时,样式将应用于整个对象,并且某些字符格式可能不会保留。例如,从TrueType样式更改为使用SHX字体的样式或其他TrueType字体会导致多行文字在整个对象中使用新字体,并且所有字符格式都将丢失。

下划线、堆叠文本或字体等可选选项可以应用于段落中的单个单词或字符。您还可以更改颜色、字体和文本高度。您可以更改文本字符之间的空格或增加字符的宽度。

使用大括号({ })仅对大括号内的文本应用格式更改。可以嵌套最多八层深度的支撑。

也可以在行或段落中输入控制代码的ASCII等效值,以指示格式或特殊字符,如公差或标注符号。

以下控制字符可用于创建插图中的文本。(For这个字符串的ASCII等价物,请参见下图中的示例。)

使用控制字符设置文本格式

下面的示例创建多行文本对象并设置其格式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
[CommandMethod("FormatMText")]
public static void FormatMText()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a multiline text object
using (MText acMText = new MText())
{
acMText.Location = new Point3d(2, 2, 0);
acMText.Width = 4.5;
acMText.Contents = "{{\\H1.5x; Big text}\\A2; over text\\A1;/\\A0;under text}";

acBlkTblRec.AppendEntity(acMText);
acTrans.AddNewlyCreatedDBObject(acMText, true);
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

使用单行文字(.NET)

添加到图形中的文字可传达各种信息。它可以是复杂的规范、标题栏信息、标签,甚至是图形的一部分。对于不需要多个字体或行的较短条目,请创建一个 DBText 对象的实例,该对象表示单行文本,便于标签。

本节中的主题

  • 创建单行文本(.NET)
  • 更改单行文字(.NET)
  • 设置文本高度(.NET)
  • 设置单行文本格式(.NET)

创建单行文本(.NET)

使用单行文字时,每一行文字都是一个不同的对象。若要创建单行文字对象,请创建 DBText 对象的实例,然后将其添加到表示模型或图纸空间的块表记录中。当你创建一个 DBText 对象的新实例时,你不需要给构造函数传递任何参数。

创建线文本

下面的示例在模型空间中的坐标(2,2,0)处创建一个单行文字对象,高度为0.5,文字字符串为“Hello,World. “.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
[CommandMethod("CreateText")]
public static void CreateText()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a single-line text object
using (DBText acText = new DBText())
{
acText.Position = new Point3d(2, 2, 0);
acText.Height = 0.5;
acText.TextString = "Hello, World.";

acBlkTblRec.AppendEntity(acText);
acTrans.AddNewlyCreatedDBObject(acText, true);
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

更改单行文字(.NET)

与任何其他对象一样,文本对象可以移动、旋转、擦除和复制。您也可以镜像文本。如果不希望文字在镜像时反转,则可以将MIRTEXT系统变量设置为0。您可以使用 TransformBy 和 Clone 方法移动、旋转和复制对象。

设置文本高度(.NET)

文字高度决定所用字体中字母的图形单位大小。该值通常表示字体的大小,但TrueType字体除外。

对于TrueType字体,为文本高度指定的值可能不表示小写字母的高度。指定的高度表示大写字母的高度加上为重音标记和非英语语言中使用的其他标记保留的重音区域。分配给大写字母和重音字符的区域的相对部分由字体设计者在设计字体时确定,因此,将因字体而异。

除了大写字母的高度和构成用户指定高度的上升区域外,TrueType字体还有一个下降区域,用于延伸到文本插入行以下的字符部分。此类字符的示例包括y、j、p、g和q。

可以使用文字样式的 TextSize 属性或文字对象的 Height 属性指定文字高度。此属性只接受正数。

设置单行文本格式(.NET)

将使用激活的文字样式创建单文字对象。可以通过更改与单行文字对象关联的文字样式或直接编辑单行文字对象的特性来更改单行文字对象的格式。不能将格式应用于单行文本对象中的单个单词和字符。

要更改与单个单行文字对象关联的文字样式,请将 TextStyleId 特性设置为新的文字样式。更改文字样式后,必须重新生成图形或更新对象才能查看图形中的更改。

除了图元的标准可编辑特性(颜色、图层、线型等)外,还可以在单行文字对象上更改以下特性:

  • HorizontalMode

    指定文本的水平对齐方式。

  • VerticalMode

    指定文本的垂直对齐方式。

  • Position

    指定文字的插入点。

  • Oblique

    指定单个文字对象的倾斜角度。

  • Rotation

    以弧度为单位指定文字的旋转角度。

  • WidthFactor

    指定文字的比例因子。

  • AlignmentPoint

    指定文字的对齐点。

  • IsMirroredInX

    指定文本是否向后显示。

  • IsMirroredInY

    指定文本是否颠倒显示。

  • TextString

    指定显示的实际文本字符串。

更改特性后,请重新生成图形或更新对象以查看所做的更改。

本节中的主题

  • 设置倾斜角度(.NET)
  • 对齐单行文字(.NET)
  • 设置文本生成标记(.NET)
设置倾斜角度(.NET)

倾斜角度决定文本的向前或向后倾斜。角度表示相对于其垂直轴的偏移(90度)。要设置倾斜角度,请使用 ObliquingAngle 属性更改文本样式或文本对象的 Oblique 属性。必须以弧度为单位提供倾斜角。正角度表示向右倾斜,负值将添加 2*PI 以将其转换为正等效值。

创建倾斜文本

这个例子创建了一个单行文本对象,然后将其倾斜45度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[CommandMethod("ObliqueText")]
public static void ObliqueText()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a single-line text object
using (DBText acText = new DBText())
{
acText.Position = new Point3d(3, 3, 0);
acText.Height = 0.5;
acText.TextString = "Hello, World.";

// Change the oblique angle of the text object to 45 degrees(0.707 in radians)
acText.Oblique = 0.707;

acBlkTblRec.AppendEntity(acText);
acTrans.AddNewlyCreatedDBObject(acText, true);
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}
对齐单行文字(.NET)

您可以水平和垂直对齐单行文字。左对齐是默认设置。要设置水平和垂直对齐选项,请使用 HorizontalMode 和 VerticalMode 属性。

通常,当文字对象关闭时,文字对象的位置和对齐点将根据其对正和文字样式进行调整。但是,内存中文本对象的对齐方式不会自动更新。调用 AdjustAlignment 方法,根据当前属性值更新文本对象的对齐方式。

重新对齐文本

下面的示例创建一个单行文本( DBText )对象和一个点( DBPoint )对象。点对象将设置为文字对齐点,并更改为红色十字准线,使其可见。文本对齐方式将更改,并显示一个消息框,以便暂停宏的执行。这使您可以查看更改文本对齐方式的影响。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
[CommandMethod("TextAlignment")]
public static void TextAlignment()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

string[] textString = new string[3];
textString[0] = "Left";
textString[1] = "Center";
textString[2] = "Right";

int[] textAlign = new int[3];
textAlign[0] = (int)TextHorizontalMode.TextLeft;
textAlign[1] = (int)TextHorizontalMode.TextCenter;
textAlign[2] = (int)TextHorizontalMode.TextRight;

Point3d acPtIns = new Point3d(3, 3, 0);
Point3d acPtAlign = new Point3d(3, 3, 0);

int nCnt = 0;

foreach (string strVal in textString)
{
// Create a single-line text object
using (DBText acText = new DBText())
{
acText.Position = acPtIns;
acText.Height = 0.5;
acText.TextString = strVal;

// Set the alignment for the text
acText.HorizontalMode = (TextHorizontalMode)textAlign[nCnt];

if (acText.HorizontalMode != TextHorizontalMode.TextLeft)
{
acText.AlignmentPoint = acPtAlign;
}

acBlkTblRec.AppendEntity(acText);
acTrans.AddNewlyCreatedDBObject(acText, true);
}

// Create a point over the alignment point of the text
using (DBPoint acPoint = new DBPoint(acPtAlign))
{
acPoint.ColorIndex = 1;

acBlkTblRec.AppendEntity(acPoint);
acTrans.AddNewlyCreatedDBObject(acPoint, true);

// Adjust the insertion and alignment points
acPtIns = new Point3d(acPtIns.X, acPtIns.Y + 3, 0);
acPtAlign = acPtIns;
}

nCnt = nCnt + 1;
}

// Set the point style to crosshair
Application.SetSystemVariable("PDMODE", 2);

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}
设置文本生成标记(.NET)

文本生成标志指定文本是向后显示还是上下颠倒显示。使用 FlagBits 属性定义文本样式是控制文本的显示是向后显示还是上下颠倒显示,或者使用文本对象的 IsMirroredInX 和 IsMirroredInY 属性分别控制文本对象。

如果您希望文本向后显示,请将 FlagBits 设置为2;如果文本应该颠倒显示,请将 FlagBits 设置为4。使用值6可同时向后和颠倒显示文本。如果您正在修改文本对象,如果您希望文本向后显示,请将 IsMirroredInX 设置为 TRUE ,如果您希望文本上下显示,请将 IsMirroredInY 设置为TRUE。

向后显示文本

下面的示例创建一个单行文本对象,然后使用 IsMirroredInX 属性将其设置为向后显示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[CommandMethod("BackwardsText")]
public static void BackwardsText()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the Block table for read
BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
OpenMode.ForRead) as BlockTable;

// Open the Block table record Model space for write
BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
OpenMode.ForWrite) as BlockTableRecord;

// Create a single-line text object
using (DBText acText = new DBText())
{
acText.Position = new Point3d(3, 3, 0);
acText.Height = 0.5;
acText.TextString = "Hello, World.";

// Display the text backwards
acText.IsMirroredInX = true;

acBlkTblRec.AppendEntity(acText);
acTrans.AddNewlyCreatedDBObject(acText, true);
}

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

使用文本样式(.NET)

图形中的所有文本都有一个与之关联的样式。输入文本时,AutoCAD将使用当前文本样式,该样式用于设置字体、大小、角度、方向和其他文本特征。可以使用或修改默认样式,也可以创建和加载新样式。创建样式后,可以修改其属性,或在不再需要时将其删除。

本节中的主题

  • 创建和修改文本样式(.NET)
  • 指定字体(.NET)
  • 使用TrueType字体(.NET)
  • 使用Unicode和大字体(.NET)
  • 替代字体(.NET)

创建和修改文本样式(.NET)

新文字继承当前文字样式的高度、宽度因子、倾斜角度和文字生成特性。要创建文本样式,请创建 TextStyleTableRecord 对象的新实例。使用 Name 特性为新文字样式指定名称。然后打开 TextStyleTable 对象进行写入,并使用 Add 方法创建新的文本样式。

样式名称可以包含字母、数字和特殊字符美元符号($)、下划线(_)和连字符(-)。AutoCAD将字符转换为字符。如果不输入样式名称,新样式将没有名称。

可以通过更改 TextStyleTableRecord 对象的属性来修改现有样式。如果你想使用当前的文本样式,使用 Database 对象的 TextStyle 属性,它保存了当前文本样式的对象id。

You can also update existing text of that style type to reflect the changes. Use the following properties to modify a TextStyleTableRecord object:
您还可以更新该样式类型的现有文本以反映更改。使用以下属性修改 TextStyleTableRecord 对象:

  • BigFontFileName
    指定用于非ASCII字符集的特殊形状定义文件。

  • FileName

    指定与字体(字符样式)关联的文件。

  • FlagBits

    指定反向文字、倒置文字或同时指定两者。

  • Font

    指定文字样式的字体、粗体、斜体、字符集、间距和族设置。

  • IsVertical

    指定垂直或水平文本。

  • ObliquingAngle

    指定字符的倾斜度。

  • TextSize

    指定字符高度。

  • XScale

    指定字符的扩展或压缩。

如果更改现有样式的字体或方向,则使用该样式的所有文本都将更改为使用新的字体或方向。更改文字高度、宽度因子和倾斜角度不会更改现有文字,但会更改后续创建的文字对象。

注意:必须重新生成图形才能查看对上述属性的任何更改。

指定字体(.NET)

字体定义组成每个字符集的文本字符的形状。一种字体可以被多个样式使用。使用 FileName 属性设置文本样式的字体文件。可以将TrueType或AutoCAD编译的SHX字体指定给文字样式。

设置文本字体

下面的示例使用活动文本样式的 Font 属性获取当前字体值,然后将字体的字样更改为“PlayBill”。若要查看更改字体的效果,请在运行示例之前向当前绘图中添加一些多行或单行文本。请注意,如果您的系统上没有PlayBill字体,则需要替换一种现有的字体,以使此示例正常工作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
[CommandMethod("UpdateTextFont")]
public static void UpdateTextFont()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the current text style for write
TextStyleTableRecord acTextStyleTblRec;
acTextStyleTblRec = acTrans.GetObject(acCurDb.Textstyle,
OpenMode.ForWrite) as TextStyleTableRecord;

// Get the current font settings
Autodesk.AutoCAD.GraphicsInterface.FontDescriptor acFont;
acFont = acTextStyleTblRec.Font;

// Update the text style's typeface with "PlayBill"
Autodesk.AutoCAD.GraphicsInterface.FontDescriptor acNewFont;
acNewFont = new
Autodesk.AutoCAD.GraphicsInterface.FontDescriptor("PlayBill",
acFont.Bold,
acFont.Italic,
acFont.CharacterSet,
acFont.PitchAndFamily);

acTextStyleTblRec.Font = acNewFont;

acDoc.Editor.Regen();

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

使用TrueType字体(.NET)

TrueType字体在图形中始终显示为填充字体;但是,打印时,TEXTFILL系统变量控制是否填充字体。默认情况下,TEXTFILL设置为1以打印填充字体。将图形导出为AutoCAD®格式并在AutoCAD设备上打印时,将按设计打印字体。

使用Unicode和大字体(.NET)

AutoCAD支持Unicode字符编码标准。Unicode字体可以包含65,535个字符,具有多种语言的形状。产品附带的所有AutoCAD SHX形状字体都支持Unicode字体。

某些字母表的文本文件包含数千个非ASCII字符。为了容纳此类文本,AutoCAD支持一种特殊类型的形状定义,称为大字体文件。您可以将样式设置为同时使用常规文件和大字体文件。使用 FileName 属性指定普通字体。使用 BigFontFileName 属性指定大字体。

注意:字体文件名不能包含逗号。

AutoCAD允许您指定在无法找到指定字体文件时使用的替代字体。使用FONTALT系统变量和应用程序的 SetSystemVariable 成员方法更改所使用的替换字体。

更改字体文件

下面的示例代码更改 FileName 和 BigFontFileName 属性。您需要将本示例中列出的路径信息替换为适合您系统的路径和文件名。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[CommandMethod("ChangeFontFiles")]
public static void ChangeFontFiles()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;

// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Open the current text style for write
TextStyleTableRecord acTextStyleTblRec;
acTextStyleTblRec = acTrans.GetObject(acCurDb.Textstyle,
OpenMode.ForWrite) as TextStyleTableRecord;

// Change the font files used for both Big and Regular fonts
acTextStyleTblRec.BigFontFileName = "C:/AutoCAD/Fonts/bigfont.shx";
acTextStyleTblRec.FileName = "C:/AutoCAD/Fonts/italic.shx";

// Save the changes and dispose of the transaction
acTrans.Commit();
}
}

替代字体(.NET)

当AutoCAD找不到图形中指定的字体时,可以指定要替换为其他字体的字体或作为默认字体。

用于图形中文本的字体由文本样式确定,对于 MText ,则由应用于文本部分的各个字体格式确定。

您可以使用字体映射表来确保您的绘图仅使用某些字体,或将您使用的字体转换为其他字体。您可以使用这些字体映射表来强制执行公司字体标准,或方便脱机打印。AutoCAD附带默认字体映射表。您可以使用任何ASCII文本编辑器编辑此文件。还可以使用FONTMAP系统变量指定不同的字体映射表文件。

指定备选默认字体

如果图形指定的字体当前不在系统中,AutoCAD将自动替换指定为备用字体的字体。默认情况下,AutoCAD使用simplex.shx文件。但是,如有必要,您可以指定其他字体。使用FONTALT系统变量设置备用字体文件名。

如果使用的文字样式使用大字体,则可以使用FONTALT系统变量将其映射到另一种字体。字体映射必须在成对的字体文件中完成:txt.shx,bigfont.shx。

如果AutoCAD在打开图形时找不到字体文件,它将应用一组默认的字体替换规则。

使用Unicode字符、控制代码和特殊字符(.NET)

可以在文本字符串中使用Unicode字符、控制代码和特殊字符来表示符号。(All必须输入非文本字符作为其ASCII等价物。)

可以通过输入以下Unicode字符串来创建特殊字符:

Unicode字符描述

Unicode character Description
\U+00B0 度数符号
\U+00B1 正/负公差符号
\U+2205 直径标注符号

除了对特殊字符使用Unicode字符外,还可以通过在文本字符串中包含控制信息来指定特殊字符。使用一对百分比符号(%%)引入每个控制序列。例如,以下控制代码使用标准AutoCAD文本和字体来绘制字符数nnn:

1
%%nnn

这些控制代码仅适用于标准AutoCAD文本字体:

控制代码说明

Control code Description
%%o 打开和关闭划线模式
%%u 打开和关闭下划线模式
%%d 绘制度数符号
%%p 绘制正负公差符号
%%c 绘制直径标注符号
%%% 绘制单个百分比符号

拼写检查(.NET)

在拼写检查过程中,AutoCAD会将图形中的单词与当前主词典中的单词进行匹配。您添加的任何单词都存储在拼写检查时最新的自定义词典中。例如,可以添加专有名称,以便AutoCAD不再将其识别为拼写错误的单词。

要检查另一种语言的拼写,您可以更改为其他主词典。

AutoCAD.NET API中没有提供检查拼写的方法。但是,可以使用DCTMAIN系统变量指定其他主字典,或使用DCTCUST系统变量指定其他自定义字典。

注:翻译自ObjectARX: Managed .NET Developer’s Guide,且只保留了C#部分的代码