使用CadLib实现CAD(dxf、dwg格式)文件的读取和显示 【转】
参考文章:CadLib 3.5 documentationhttps://www.woutware.com/doc/cadlib3.5/Index.aspx
读取:定义DxfModel类型的变量model,使用DxfReader或DwgReader的Read(String)读取dxf或dwg格式的CAD文件filename。
显示:使用GIDGraphics3D类来显示CAD文件,基本步骤:
1、使用CreateDrawables(DxfModel)创建中间可绘制对象(点/线/折线)。
2、使用BoundingBox(Bounds3D)方法获取bounding box。
3、使用GetScaleTransform(Point3D, Point3D, Point3D, Point3D, Point3D, Point3D)计算将绘图拟合到显示矩形中所需的缩放变换,使用To2Dtransform属性设置结果。(写一个函数CalculateTo2DTransform)
4、使用Draw(Graphics, Rectangle)绘制中间可绘制对象。
注意:需要重写控件的Resize和Paint事件。
- //Read and view CAD file 读和显示CAD文件
- private Matrix4D modelTransform = Matrix4D.Identity;
- private GDIGraphics3D gdiGraphics3D;
- private DxfModel model;//定义DxfModel对象
- private Bounds3D bounds;
- private string filename;
- //计算GDIGraphics3D的属性To2DTransform
- private void CalculateTo2DTransform()
- {
- if (bounds != null)
- {
- //计算将CAD文件放入显示矩阵中需要的缩放比例变换
- Matrix4D to2DTransform = DxfUtil.GetScaleTransform(
- bounds.Corner1,
- bounds.Corner2,
- bounds.Center,
- new Point3D(0d, this.xtraTabPage3.Height, 0d),
- new Point3D(this.xtraTabPage3.Width, 0d, 0d),
- new Point3D(this.xtraTabPage3.Width / 2, this.xtraTabPage3.Height / 2, 0d)
- );
- gdiGraphics3D.To2DTransform = to2DTransform * modelTransform;
- }
- }
- //打开CAD文件
- private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
- {
- //选取要打开的CAD文件
- OpenFileDialog dialog = new OpenFileDialog();
- dialog.Filter = "AutoCad files (*.dwg, *.dxf)|*.dxf;*.dwg";
- if (dialog.ShowDialog() == DialogResult.OK)
- {
- filename = dialog.FileName;
- }
- if (!string.IsNullOrEmpty(filename))
- {
- try
- {
- //通过文件扩展名判断CAD文件是dwg格式还是dxf格式
- string extension = Path.GetExtension(filename);
- if (string.Compare(extension, ".dwg", true) == 0)
- model = DwgReader.Read(filename);
- else
- model = DxfReader.Read(filename);
- //将控件的标签添加上文件名
- this.xtraTabPage3.Text = "二维仿真(" + Path.GetFileName(filename) + ")";
- //设置控件背景为黑色
- this.xtraTabPage3.BackColor = System.Drawing.Color.Black;
- //使用GDIGraphics3D绘制CAD文件的方法
- //创建中间可绘制对象
- gdiGraphics3D.CreateDrawables(model);
- //获得bounding box
- bounds = new Bounds3D();
- gdiGraphics3D.BoundingBox(bounds, modelTransform);
- //计算GDIGraphics3D的属性To2DTransform
- CalculateTo2DTransform();
- //响应控件的Paint事件,画CAD文件
- }
- catch (Exception ex)
- {
- MessageBox.Show("文件有错!请用AutoCad打开,通过“文件-核查”尝试修复。错误信息:" + ex.Message);
- }
- }
- }
- //xtraTabPage3控件的Paint事件,画CAD文件
- private void xtraTabPage3_Paint(object sender, PaintEventArgs e)
- {
- gdiGraphics3D.Draw(e.Graphics, this.xtraTabPage3.ClientRectangle);
- }
- //使绘制的CAD文件适应屏幕
- private void xtraTabPage3_Resize(object sender, EventArgs e)
- {
- base.OnResize(e);
- CalculateTo2DTransform();
- this.xtraTabPage3.Invalidate();
- }
http://blog.csdn.net/zjzytnn/article/details/53708655
饮水思源,不忘初心。
要面包,也要有诗和远方。