本文介绍在Vistual Studio 2022中使用Avalonia和集成AnyCAD Rapid AvaloniaUI三维控件的过程。
0 初始化环境
安装Avalonia.Templates
dotnet new install Avalonia.Templates
若之前安装过可忽略此步骤。
1 创建项目
选择创建AvaloniaUI项目
选一下.NET6版本和Avalonia版本
2 配置项目
2.1 安装AnyCAD AvaloniaUI组件
从nuget.org上安装AnyCAD AvaloniaUI。
2.2 增加HDPI支持
修改app.manifest,在尾部增加 asmv3:application 相关配置
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"><!-- 新增加的内容,支持HDPI --><asmv3:application xmlns:asmv3="urn:schemas-microsoft-com:asm.v3"><asmv3:windowsSettings><dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware><dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2,permonitor</dpiAwareness></asmv3:windowsSettings></asmv3:application>
</assembly>
3 设计界面
在MainWindow.axaml里面集成AnyCAD Rapid控件:
- 首先引入程序集: AnyCAD.Avalonia.NET6:
xmlns:anycad="clr-namespace:AnyCAD.AvaloniaUI;assembly=AnyCAD.Avalonia.NET6"
- 设计布局
直接加个Button和三维控件。完整的xaml如下:
<Window xmlns="https://github.com/avaloniaui"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:anycad="clr-namespace:AnyCAD.AvaloniaUI;assembly=AnyCAD.Avalonia.NET6"mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"x:Class="AnyCAD.AvaloniaApp.MainWindow"Title="AnyCAD.AvaloniaApp"><StackPanel><Button Content="打开" Width="160"/><anycad:RenderControl x:Name="mRenderView" Width="800" Height="600"></anycad:RenderControl></StackPanel>
</Window>
4 初始化控件
在Program.cs修改初始化代码, Main函数做修改
[STAThread]public static void Main(string[] args){// 初始化AnyCAD.Foundation.GlobalInstance.Initialize();BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);// 释放资源AnyCAD.Foundation.GlobalInstance.Destroy();}
运行一下:
5 显示模型
- MainWindow函数中响应一下Buttond的Click事件
public partial class MainWindow : Window{public MainWindow(){InitializeComponent(); }public void OnOpen(object sender, RoutedEventArgs e){var dlg = new OpenFileDialog();dlg.Filters.Add(new FileDialogFilter() { Name = "Model Files", Extensions = { "step", "stp", "iges", "igs" } });var result = dlg.ShowAsync(this);if (result == null)return;string fileName = result.Result[0];var shape = ShapeIO.Open(fileName);if(shape != null){var node = BrepSceneNode.Create(shape, null, null);var scene = mRenderView.Scene;scene.AddNode(node);mRenderView.ViewContext.RequestUpdate(EnumUpdateFlags.Scene);}}}
再运行一下,打开个模型
6 总结
AvaloniaUI一款优秀的跨平台.NET UI库,结合AnyCAD Rapid .NET for AvaloniaUI,就可以快速开发跨平台的三维应用。
本文完整代码:anycad.rapid.net.sample