1、下载CadLib相关dll文件,主要用到的:WW.dll、WW.Cad.dll、WW.GL.dll
2、程序中引用dll库。
3、创建WPF程序,使用Canvas来加载dwg文件,支持拖动和放大缩小。
4、部分代码:
public void Init(string filename)
{
try
{
string extension = System.IO.Path.GetExtension(filename);
if (string.Compare(extension, ".dwg", true) == 0)
{
model = DwgReader.Read(filename);
}
else
{
model = DxfReader.Read(filename);
}
#region calculate the model's bounds to determine a proper dots per inch
// The dots per inch value is important because it determines the eventual pen thickness.
graphicsConfig = (GraphicsConfig)GraphicsConfig.WhiteBackgroundCorrectForBackColor.Clone();
BoundsCalculator boundsCalculator = new BoundsCalculator();
if (model.ActiveLayout == null || model.Header.ShowModelSpace)
{
boundsCalculator.GetBounds(model);
}
else
{
boundsCalculator.GetBounds(model, model.ActiveLayout);
}
bounds = boundsCalculator.Bounds;
WW.Math.Vector3D delta = bounds.Delta;
Size estimatedCanvasSize = new Size(500d, 500d);
double estimatedScale = Math.Min(estimatedCanvasSize.Width / delta.X, estimatedCanvasSize.Height / delta.Y);
graphicsConfig.DotsPerInch = 100d / estimatedScale;
#endregion
graphicsCache = new WireframeGraphics2Cache(false, false);
graphicsCache.Config = graphicsConfig;
if (model.ActiveLayout == null || model.Header.ShowModelSpace)
{
graphicsCache.CreateDrawables(model, Matrix4D.Identity);
}
else
{
graphicsCache.CreateDrawables(model, model.ActiveLayout);
}
wpfGraphics = new WpfWireframeGraphics3DUsingDrawingVisual();
wpfGraphics.Config = graphicsConfig;
this.Dispatcher.Invoke(() => {
canvas.Children.Add(wpfGraphics.Canvas);
canvas.SizeChanged += canvas_SizeChanged;
});
UpdateWpfGraphics();
}
catch (Exception ex)
{
this.Dispatcher.Invoke(() => {
msg.Text = $"文件加载出现异常,详细:{ex.Message}";
});
}
}
如果想设置文字颜色,在Read后增加代码:
foreach (DxfEntity entity in model.Entities)
{
// 检查实体是否为DxfText或DxfMText
if (entity is DxfText textEntity)
{
// 设置DxfText的颜色
textEntity.Color = EntityColors.Red; // 替换为你想要的颜色
}
else if (entity is DxfMText mTextEntity)
{
// 设置DxfMText的颜色
mTextEntity.Color = EntityColors.Red; // 替换为你想要的颜色
}
}
5、Demo地址
WPF程序通过CadLib4加载CAD.dwg格式文件资源-CSDN文库