基于Visual C#的AutoCAD开发——实例11 绘制基本图形
除了可以获取CAD文件中的图形对象外,还可以通过程序在CAD中绘制图形,特别是对于一些重复、繁琐的操作使用程序设计可以很大程度上提高工作效率。在CAD中绘制图形主要通过AcadModelSpace接口来实现,通过该接口程序设计者可以通过程序语言在CAD中绘制线条、面、三维实体等。下面介绍一些常用绘图函数:
1、绘制直线
绘制直线主要通过ModelSpace的AddLine()方法来实现。添加一个按钮,设置其Name和Text属性都为“绘制直线”,为其Click事件添加代码如下:
private void 绘制直线_Click(object sender, EventArgs e)
{
Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
double[] startPoint = new double[3];
double[] endPoint = new double[3];
startPoint[0] = 0; startPoint[1] = 0; startPoint[2] = 0;
endPoint[0] = 100; endPoint[1] = 100; endPoint[2] = 0;
AcadDoc.ModelSpace.AddLine(startPoint, endPoint);
}
其中,startPoint和endPoint为一个长度为3的Double类型数组,分别表示直线的起点坐标和终点坐标。运行程序,其显示结果如下图所示:
2、添加文字
添加文字主要通过ModelSpace的AddLine()方法来实现。添加一个按钮,设置其Name和Text属性都为“添加文字”,为其Click事件添加代码如下:
private void 添加文字_Click(object sender, EventArgs e)
{
Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
string textString="Hello";
double[] textInsertPoint = new double[3];
double textHeight=2.0;
textInsertPoint[0] = 0; textInsertPoint[1] = 0; textInsertPoint[2] = 0;
AcadDoc.ModelSpace.AddText(textString, textInsertPoint, textHeight);
}
其中,textString表示要添加的文字内容,textInsertPoint为文字的插入点,textHeight为文字的高度。运行程序,其显示结果如下图所示:
3、绘制三维多段线
三维多段线在三维建模中应用非常多,有时候作为主要的结构线条表示,有时候作为辅助线条来建立其他模型。绘制三维多段线主要通过ModelSpace的Add3DPoly()方法来实现。下面以一个将多段线转换为三维多段线的例子来说明如何绘制三维多段线。首先添加一个按钮,设置其Name和Text属性都为“绘制三维多段线”,然后为其Click事件添加代码如下:
private void 绘制三维多段线_Click(object sender, EventArgs e)
{
handle01:
Microsoft.VisualBasic.Interaction.AppActivate(AcadApp.Caption);
object returnObj, pickPoint;
string pickPrompt = "选取Polyline对象!";
AcadDoc.Utility.GetEntity(out returnObj, out pickPoint, pickPrompt);
AcadObject returnCADObj = (AcadObject)returnObj;
if (returnCADObj.ObjectName != "AcDbPolyline") goto handle01;
AcadLWPolyline returnLWPolyline = (AcadLWPolyline)returnCADObj;
if (!returnLWPolyline.Closed)
{
MessageBox.Show("选取的多段线没有闭合!");
goto handle01;
}
Double[] LWPolylineCoords, create3DPolyCoords;
LWPolylineCoords = (Double[])returnLWPolyline.Coordinates;
int i;
create3DPolyCoords = new Double[3 * LWPolylineCoords.Length / 2];
for (i = 0; i < LWPolylineCoords.Length / 2; i++)
{
create3DPolyCoords[3 * i] = LWPolylineCoords[2 * i];
create3DPolyCoords[3 * i + 1] = LWPolylineCoords[2 * i + 1];
create3DPolyCoords[3 * i + 2] = 0;
}
AcadDoc.ModelSpace.Add3DPoly(create3DPolyCoords);
}
其中,Add3DPoly()方法绘制三维多段线要求其参数为长度为3*n的double数组。运行程序,其显示结果如下图所示:
添加其他图形的方式和前面介绍的基本上一样,只需要设置所对应函数的相应参数即可,在此就不一一介绍了。