Create Objects创建对象
AutoCAD often offers several differentways to create the same graphical object. While the .NET API does not offer thesame combinations of creating objects,it does offer a basic object constructorfor each object type but also offers overrides for many of the objectconstructors as well.
对于创建相同的图形对象,AutoCAD常常提供几个不同的方法。.NET API虽然没有提供相同的创建方法组合,但为每个对象类型都提供了基本对象构造函数,并且对许多对象的构造函数还提供了重载。
For example,in AutoCAD there are fourdifferent ways you can create a circle: (1) by specifying the center andradius,(2) by two points defining the diameter,(3) by three points definingthe circumference,or (4) by two tangents and a radius. However,in .NET APIthere is two creation methods provided to create a circle. One method acceptsno parameters,while the second requires a center point,the normal directionfor the circle,and a radius.
例如,AutoCAD中绘制一个圆有4个不同的方法:(1)通过指定圆心和半径;(2)通过两点定义的直径;(3)通过三个点定义的圆周;(4)通过两条切线和半径。可是,在.NETAPI中,创建一个圆有两个方法,一个方法是无参数方法,另一个方法需要圆心、方向和半径。
Note Objects are created using the New keywordand then appended to the parent object using Add or AppendEntity based on if you are working with acontainer (symbol table or dictionary) or a BlockTableRecord object.
注意:对象通过使用New关键字创建,然后使用Add或AppendEntity方法追加到其父对象中。具体是使用Add方法还是使用AppendEntity方法,取决于父对象是一个容器对象(符号表或字典)还是BlockTableRecord对象。
Set the default property values for anobject 设置对象的默认属性值
When a new graphical object is created,the following entity property values are assigned the current entity values definedin the database of the current document:
一个新对象创建时,下列实体属性值被设置成当前文档数据库所定义的当前实体值:
·Color 颜色
·Layer 图层
·Linetype 线型
·Linetype scale 线形比例
·Lineweight 线宽
·Plot style name 打印样式名字
·Visibility 可见性
·Transparency 透明度
Note If the properties of an object need to beset to the default values of the current database,call the SetDatabaseDefaults method of the object to be changed.
注意:如果需要将对象的属性设置为当前数据库的默认值,可调用要修改对象的SetDatabaseDefaults方法。
Topics in this section本节主题
·Determine the Parent Object 确定父对象
·Create Lines 创建直线
·Create Curved Objects 创建曲线类对象
·Create Point Objects 创建点对象
·Create Solid-Filled Areas 创建实体填充区域
·Work with Regions 使用面域
·Create Hatches 创建图案填充
1、Determinethe Parent Object确定父对象
Graphical objects are appended to aBlockTableRecord object,such as Model or Paper space. You reference the blocksthat represent Model and Paper space through the BlockTable object. If you wantto work in the current space instead of a specific space,you get the ObjectIdfor the current space from the current database with the CurrentSpaceId property.
图形对象被添加到像模型空间或图纸空间这样的BlockTableRecord对象中。我们通过BlockTable对象引用代表Model空间或Paper空间的块。如果要使用当前空间而不是指定某空间,可以使用CurrentSpaceId属性从当前数据库获取当前空间的ObjectId。
The ObjectId for the block table recordsof Model and Paper space can be retrieved from the BlockTable object using aproperty or the GetBlockModelSpaceId and GetBlockPaperSpaceId methods of the SymbolUtilityServicesclass under the DatabaseServices namespace.
块表记录Model空间和块表记录Paper空间的ObjectId可以使用属性从BlockTable对象取得,或者使用DatabaseServices命名空间下SymbolUtilitySErvices类的GetBlockModelSpaceId方法和GetBlockPaperSpaceId方法取得。
Access Model space,Paper space or thecurrent space 访问模型空间、图纸空间或当前空间
The following example demonstrates how toaccess the block table records associated with Model space,Paper space or thecurrent space. Once the block table record is referenced,a new line is addedto the block table record.
下面这个例子演示如何访问与Model空间、Paper空间或当前空间关联的块表记录。获得对块表记录的引用后,往里添加一条新直线。
VB.NET
ImportsAutodesk.AutoCAD.Runtime
ImportsAutodesk.AutoCAD.ApplicationServices
ImportsAutodesk.AutoCAD.DatabaseServices
ImportsAutodesk.AutoCAD.Geometry
ImportsAutodesk.AutoCAD.EditorInput
<CommandMethod("AccessSpace")>_
Public SubAccessSpace()
'' Get the current document and database
Dim acDoc As Document =Application.DocumentManager.MdiActiveDocument
Dim acCurDb As Database = acDoc.Database
'' Start a transaction
Using acTrans As Transaction =acCurDb.TransactionManager.StartTransaction()
'' Open the Block table for read
Dim acBlkTbl As BlockTable
acBlkTbl =acTrans.GetObject(acCurDb.BlockTableId,OpenMode.ForRead)
'' Open the Block table record for read
Dim acBlkTblRec As BlockTableRecord
'' Request which table record to open
Dim pKeyOpts As PromptKeywordOptions =New PromptKeywordOptions("")
pKeyOpts.Message = vbLf & "Enterwhich space to create the line in "
pKeyOpts.Keywords.Add("Model")
pKeyOpts.Keywords.Add("Paper")
pKeyOpts.Keywords.Add("Current")
pKeyOpts.AllowNone = False
pKeyOpts.AppendKeywordsToMessage = True
Dim pKeyRes As PromptResult =acDoc.Editor.GetKeywords(pKeyOpts)
If pKeyRes.StringResult ="Model" Then
'' Get the ObjectID for Model spacefrom the Block table
acBlkTblRec =acTrans.GetObject(acBlkTbl(BlockTableRecord.ModelSpace),_
OpenMode.ForWrite)
ElseIf pKeyRes.StringResult ="Paper" Then
'' Get the ObjectID for Paper spacefrom the Block table
acBlkTblRec =acTrans.GetObject(acBlkTbl(BlockTableRecord.PaperSpace),255);">OpenMode.ForWrite)
Else
'' Get the ObjectID for the currentspace from the database
acBlkTblRec =acTrans.GetObject(acCurDb.CurrentSpaceId,255);"> End If
'' Create a line that starts at 2,5 andends at 10,7
Dim acLine As Line = New Line(NewPoint3d(2,5,0),255);"> NewPoint3d(10,7,0))
'' Add the new object to the block tablerecord and the transaction
acBlkTblRec.AppendEntity(acLine)
acTrans.AddNewlyCreatedDBObject(acLine,True)
'' Save the new line to the database
acTrans.Commit()
End Using
End Sub
C#
usingAutodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
usingAutodesk.AutoCAD.DatabaseServices;
usingAutodesk.AutoCAD.Geometry;
usingAutodesk.AutoCAD.EditorInput;
[CommandMethod("AccessSpace")]
public static voidAccessSpace()
{
// 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;
OpenMode.ForRead) as BlockTable;
// Open the Block table record for read
BlockTableRecord acBlkTblRec;
// Request which table record to open询问打开哪条表记录(空间)
PromptKeywordOptions pKeyOpts = newPromptKeywordOptions("");
pKeyOpts.Message = "\nEnter whichspace 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 spacefrom the Block table
//从Block表获取Model空间的ObjectID
acBlkTblRec =acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],255);">OpenMode.ForWrite) as BlockTableRecord;
}
else if (pKeyRes.StringResult =="Paper")
// Get the ObjectID for Paper spacefrom the Block table
//从Block表获取Paper空间的ObjectID
acBlkTblRec =acTrans.GetObject(acBlkTbl[BlockTableRecord.PaperSpace],255);"> else
// Get the ObjectID for the currentspace from the database
// Create a line that starts at 2,255);"> //从2,5到10,7画一条直线
Line acLine = new Line(new Point3d(2,255);"> new Point3d(10,0));
// Add the new object to the block tablerecord and the transaction
acBlkTblRec.AppendEntity(acLine);
// Save the new line to the database保存新直线到数据库
acTrans.Commit();
}
VBA/ActiveX Code Reference
' Define the valid keywords
Dim keywordList As String
keywordList = "Model PaperCurrent"
' Call InitializeUserInput to setup thekeywords
ThisDrawing.Utility.InitializeUserInput 1,keywordList
' Get the user input
Dim retVal As Variant
retVal =ThisDrawing.Utility.GetKeyword(vbLf & _
"Enterwhich space to create the line in " & _
"[Model/Paper/Current]: ")
' Get the entered keyword
Dim strVal As String
strVal = ThisDrawing.Utility.GetInput
Dim acSpaceObj As Object
If strVal = "Model" Or _
(strVal = "Current" AndThisDrawing.ActiveSpace = acModelSpace) Then
'' Get the Model space object
Set acSpaceObj = ThisDrawing.ModelSpace
'' Get the Paper space object
Set acSpaceObj = ThisDrawing.PaperSpace
'' Create a line that starts at 2,255);"> Dim acLine As AcadLine
Dim dPtStr(0 To 2) As Double
dPtStr(0) = 2: dPtStr(1) = 5: dPtStr(2) =0#
Dim dPtEnd(0 To 2) As Double
dPtEnd(0) = 10: dPtEnd(1) = 7: dPtEnd(2) =0#
Set acLine = acSpaceObj.AddLine(dPtStr,dPtEnd)
End Sub
2、CreateLines创建直线
The line is the most basic object inAutoCAD. You can create a variety of lines—single lines,and multiple linesegments with and without arcs. In general,you draw lines by specifyingcoordinate points. Lines when created,inherit the current settings from thedrawing database,such as layer,linetype and color.
直线是AutoCAD中最基本的对象。我们可以创建各种不同的直线——单一的直线、带圆弧或不带圆弧的复合线段。通常是通过指定坐标点来绘制直线。创建的直线从当前数据库继承当前设置,如图层、线型及颜色等。
To create a line,you create a newinstance of one of the following objects:
创建一条直线,就是创建下列对象之一的一个新实例:
Line
Creates a line. 创建一条直线;
Polyline
Creates a 2D lightweight polyline. 创建二维轻量级多段线;
MLine
Creates a multiline. 创建多线;
Polyline2D
Creates a 2D polyline. 创建二维多段线;
Polyline3D
Creates a 3D polyline. 创建三维多段线
Note Polyline2D objects are the legacy polylineobjects that were in AutoCAD prior to Release 14,and the Polyline objectrepresents the new optimized polyline that was introduced with AutoCAD Release14.
注意:Polyline2D对象是Release14之前版本AutoCAD中的传统多段线对象,Polyline对象代表AutoCAD Release 14版引入的新的优化多段线。
Topics in this section本小节主题
·Create a Line Object 创建一个直线对象
·Create a Polyline object 创建一个多段线对象
2.1、Create a Line Object创建一个直线对象
This example adds a line that starts at(5,0) and ends at (12,3,0) to Model space.
本例往模型空间添加一条直线,起点(5,0),终点(12,0)。
VB.NET
<CommandMethod("AddLine")>_
Public Sub AddLine()
'' Start a transaction
'' Open the Block table for read
'' Open the Block table record Modelspace for write
'' Create a line that starts at 5,5 andends at 12,3
Dim acLine As Line = New Line(NewPoint3d(5,255);"> NewPoint3d(12,255);"> '' Add the new object to the block tablerecord and the transaction
'' Save the new object to the database
usingAutodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Geometry;
[CommandMethod("AddLine")]
public static voidAddLine()
// Start a transaction
OpenMode.ForRead) as BlockTable;
// Open the Block table record Modelspace for write
OpenMode.ForWrite)as BlockTableRecord;
// Create a line that starts at 5,255);"> Line acLine = new Line(new Point3d(5,255);"> new Point3d(12,255);"> // Save the new object to the database
}
VBA/ActiveX CodeReference
Sub AddLine()
' Define the start point
Dim ptStr(0 To 2) As Double
ptStr(0) = 5: ptStr(1) = 5: ptStr(2) = 0#
' Define the end point
Dim ptEnd(0 To 2) As Double
ptEnd(0) = 12: ptEnd(1) = 3: ptEnd(2) = 0#
' Create a Line object in model space
Dim lineObj As AcadLine
Set lineObj =ThisDrawing.ModelSpace.AddLine(ptStr,ptEnd)
ThisDrawing.Application.ZoomAll
End Sub
2.2、Create a Polyline object创建一个多段线对象
This example adds a lightweight polylinewith two straight segments using the 2D coordinates (2,4),(4,2),and (6,4) toModel space.
本例往模型空间添加一条轻量级多段线,多段线有两段线段,二维坐标为(2,4)、(4,2)和(6,4)。
VB.NET
<CommandMethod("AddLightweightPolyline")>_
Public SubAddLightweightPolyline()
Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument
'' Create a polyline with two segments (3points)
Dim acPoly As Polyline = New Polyline()
acPoly.AddVertexAt(0,New Point2d(2,0)
acPoly.AddVertexAt(1,New Point2d(4,255);"> acPoly.AddVertexAt(2,New Point2d(6,255);"> acBlkTblRec.AppendEntity(acPoly)
acTrans.AddNewlyCreatedDBObject(acPoly,255);">[CommandMethod("AddLightweightPolyline")]
public static voidAddLightweightPolyline()
OpenMode.ForRead)as BlockTable;
// Create a polyline with two segments (3points)
Polyline acPoly = new Polyline();
acBlkTblRec.AppendEntity(acPoly);
SubAddLightWeightPolyline()
Dim plineObj As AcadLWPolyline
Dim points(0 To 5) As Double
' Define the 2D polyline points
points(0) = 2: points(1) = 4
points(2) = 4: points(3) = 2
points(4) = 6: points(5) = 4
' Create a light weight Polyline object inmodel space
Set plineObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
End Sub
3、CreateCurved Objects创建曲线类对象
You can create a variety of curved objectswith AutoCAD,including splines,helixes,circles,arcs,and ellipses. Allcurves are created on the XY plane of the current UCS.
用AutoCAD可以创建各种不同的曲线类对象,包括样条曲线、螺旋线、圆、圆弧以及椭圆等。所有这些曲线都创建在当前用户坐标系的XY平面上。
To create a curve,you create a newinstance of one of the following objects:
创建曲线,就是创建下列对象之一的一个新实例:
Arc
Creates an arc given the center point,radius,start andend angles. 已知圆心、半径、起止角,建圆弧;
Circle
Creates a circle given the center point and radius. 已知圆心、半径,建圆;
Ellipse
Creates an ellipse,given the center point,a point onthe major axis,and the radius ratio. 已知圆心、主轴上一点、半径比,建椭圆;
Spline
Creates a quadratic or cubic NURBS (nonuniform rationalB-spline) curve. 创建一条二阶或三阶不均匀有理B样条曲线;
Helix
Creates a 2D or 3D helix object. 创建二维或三维螺旋线对象;
Topics in this section本小节主题
·Create a Circle object 创建圆对象
·Create an Arc object 创建圆弧对象
·Create a Spline object 创建样条曲线对象
3.1、Createa Circle object创建圆对象
This example creates a circle in Modelspace with a center point of (2,0) and a radius of 4.25.
本例在模型空间创建一个圆,圆心(2,0),半径4.25。
VB.NET
Imports Autodesk.AutoCAD.ApplicationServices
<CommandMethod("AddCircle")>_
Public SubAddCircle()
'' Create a circle that is at 2,3 with aradius of 4.25
Dim acCirc As Circle = New Circle()
acCirc.Center = New Point3d(2,255);"> acCirc.Radius = 4.25
acBlkTblRec.AppendEntity(acCirc)
acTrans.AddNewlyCreatedDBObject(acCirc,255);">[CommandMethod("AddCircle")]
public static voidAddCircle()
// Get the current document and database获取当前文档及数据库
// Start a transaction启动事务
// Open the Block table for read以读打开块表
// 以写打开模型空间记录
// Create a circle that is at 2,255);"> //创建圆,圆心(2,3),半径4.25
Circle acCirc = new Circle();
acCirc.Center = new Point3d(2,255);"> acCirc.Radius = 4.25;
//添加新对象到块表记录及事务
acBlkTblRec.AppendEntity(acCirc);
// Save the new object to the database保存新对象到数据库
Sub AddCircle()
' Define the center point
Dim ptCen(0 To 2) As Double
ptCen(0) = 2: ptCen(1) = 3: ptCen(2) = 0#
' Create a Circle object in model space
Dim circObj As AcadCircle
Set circObj =ThisDrawing.ModelSpace.AddCircle(ptCen,4.25)
End Sub
3.2、Createan Arc object创建圆弧对象
This example creates an arc in Model spacewith a center point of (6.25,9.125,a radius of 6,start angle of 1.117 (64degrees),and an end angle of 3.5605 (204 degrees).
本例在模型空间创建一个圆弧,圆心(6.25,0),半径6,起始角1.117(64度),终止角3.5605(204度)。
VB.NET
<CommandMethod("AddArc")>_
Public Sub AddArc()
'' Create an arc that is at 6.25,9.125with a radius of 6,and
'' starts at 64 degrees and ends at 204degrees
Dim acArc As Arc = New Arc(NewPoint3d(6.25,255);"> 6,1.117,3.5605)
acBlkTblRec.AppendEntity(acArc)
acTrans.AddNewlyCreatedDBObject(acArc,255);">[CommandMethod("AddArc")]
public static voidAddArc()
OpenMode.ForRead) asBlockTable;
//以写打开模型空间记录
// Create an arc that is at 6.25,255);"> // starts at 64 degrees and ends at 204degrees
// 已知圆心、半径、起止角,建圆弧
Arc acArc = new Arc(new Point3d(6.25,3.5605);
//将新对象添加到块表记录及事务
acBlkTblRec.AppendEntity(acArc);
Sub AddArc()
ptCen(0) = 6.25: ptCen(1) = 9.125: ptCen(2)= 0#
' Create an Arc object in model space
Dim arcObj As AcadArc
Set arcObj =ThisDrawing.ModelSpace.AddArc(ptCen,6#,255);">
3.3、Createa Spline object创建样条曲线对象
This example creates a spline in Modelspace using three points (0,(5,and (10,0). The spline hasstart and end tangents of (0.5,0.5,0.0).
本例用三个点(0,0)、 (5,0)和 (10,0)在模型空间创建一条样条曲线。该样条曲线的起止点的切线方向为(0.5,0.0)。
VB.NET
<CommandMethod("AddSpline")>_
Public SubAddSpline()
'' Define the fit points for the spline
Dim ptColl As Point3dCollection = NewPoint3dCollection()
ptColl.Add(New Point3d(0,255);"> ptColl.Add(New Point3d(5,255);"> ptColl.Add(New Point3d(10,255);"> '' Get a 3D vector from the point(0.5,255);"> Dim vecTan As Vector3d = New Point3d(0.5,0).GetAsVector
'' Create a spline through (0,0) with a
'' start and end tangency of (0.5,0.0)
Dim acSpline As Spline = NewSpline(ptColl,vecTan,4,255);"> acBlkTblRec.AppendEntity(acSpline)
acTrans.AddNewlyCreatedDBObject(acSpline,255);">[CommandMethod("AddSpline")]
public static voidAddSpline()
// Define the fit points for the spline
// 定义样条曲线的拟合点
Point3dCollection ptColl = newPoint3dCollection();
ptColl.Add(new Point3d(0,255);"> ptColl.Add(new Point3d(5,255);"> ptColl.Add(new Point3d(10,255);"> // Get a 3D vector from the point(0.5,255);"> // 获取点(0.5,0)的3D矢量
Vector3d vecTan = new Point3d(0.5,0).GetAsVector();
// Create a spline through (0,255);"> // start and end tangency of (0.5,255);"> //创建通过3个点的样条曲线,且起止点的切线方向为(0.5,0.0);
//注:在公差值设置为0.0时(第5个参数),样条曲线直接通过拟合点。
Spline acSpline = new Spline(ptColl,255);"> acBlkTblRec.AppendEntity(acSpline);
// Save the new line to the database保存新对象到数据库
Sub AddSpline()
' This example creates a spline object inmodel space.
' Declare the variables needed
Dim splineObj As AcadSpline
Dim startTan(0 To 2) As Double
Dim endTan(0 To 2) As Double
Dim fitPoints(0 To 8) As Double
' Define the variables
startTan(0) = 0.5: startTan(1) = 0.5:startTan(2) = 0
endTan(0) = 0.5: endTan(1) = 0.5: endTan(2)= 0
fitPoints(0) = 1: fitPoints(1) = 1:fitPoints(2) = 0
fitPoints(3) = 5: fitPoints(4) = 5:fitPoints(5) = 0
fitPoints(6) = 10: fitPoints(7) = 0:fitPoints(8) = 0
' Create the spline
Set splineObj =ThisDrawing.ModelSpace.AddSpline _
(fitPoints,startTan,endTan)
ZoomAll
End Sub