要運行本文中的示例,請先安裝Vistual Studio 2022,社區版就可以了。
1 創建項目
選擇創建WPF應用
給程序起一個酷酷的名字,選一個酷酷的位置:
選一下.NET6
2 配置項目
從nuget.org上安裝AnyCAD Rapid SDK 2022。
3 設計界面
- 首先引入程序集:
xmlns:anycad="clr-namespace:AnyCAD.WPF;assembly=AnyCAD.WPF.NET6"
- 設計布局
給三維界面留個位置,采用經典的左右窗口。右邊用來顯示三維內容。完整的xaml如下:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
xmlns:anycad="clr-namespace:AnyCAD.WPF;assembly=AnyCAD.WPF.NET6"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="100" Width="0.3*"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<anycad:RenderControl Grid.Column="1" x:Name="mRenderCtrl"/>
</Grid>
</Window>
運行一下:
5 顯示模型
- 增加一個ViewerReady事件
<anycad:RenderControl Grid.Column="1" x:Name="mRenderCtrl" ViewerReady="mRenderCtrl_ViewerReady"/>
- 在mRenderCtrl_ViewerReady中創建一個球
private void mRenderCtrl_ViewerReady()
{
var shape = ShapeBuilder.MakeSphere(new GPnt(0, 0, 0), 100);
mRenderCtrl.ShowShape(shape, ColorTable.AliceBlue);
}
在三維控件初始化完成之前是不能進行對控件進行操作的
再運行一下:
6 資源釋放
在調試模式下,程序退出的時候在輸出窗口中,你可能會發現這樣的錯誤:
程序“[57196] WpfApp1.exe”已退出,返回值為 3221225477 (0xc0000005) 'Access violation'。
這是因為AnyCAD Rapid SDK沒有正確的釋放資源。為保證三維控件資源能夠正確釋放,程序能夠得到正常的返回值,只需要這樣加一下Startup和Exit消息:
<Application x:Class="WpfApp1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
StartupUri="MainWindow.xaml" Exit="Application_Exit" Startup="Application_Startup">
<Application.Resources>
</Application.Resources>
</Application>
代碼修改:
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
AnyCAD.Foundation.GlobalInstance.Initialize();
}
private void Application_Exit(object sender, ExitEventArgs e)
{
AnyCAD.Foundation.GlobalInstance.Destroy();
}
}
7 總結
相比WinForms程序,WPF程序需要經常在XAML和代碼之間切換,使用門檻稍高,但熟悉就好了。
.NET6為開發者帶來了高效的開發體驗,而AnyCAD Rapid SDK也一樣,通過簡單幾步即可為應用添加三維能力,讓程序顯得高大上!
AnyCAD Rapid SDK的包括三維顯示、造型、STEP/IGES讀取等場景的三維功能,能夠滿足大部分的三維工業軟件應用場景,比如CAD設計、CAE仿真、CAM加工,機器人模擬等,可以應用在建築、機械、電力、化工、自動化等多個領域。