OpenGL是針對Windows Forms開發,下面是在WPF環境下的集成方法。
(P.S. 如果只在windows下使用,其實WPF 3D或DirectX是更好的選擇)。
1.新建一個WPF項目。
2.添加以下references到項目中:
System.Windows.Forms
WindowsFormsIntegration
OpenTK
OpenTK.GLControl
3.在xaml中加入如下內容:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" Title="MainWindow" Height="500" Width="500" Loaded="Window_Loaded"> <Grid Name="grid"> <WindowsFormsHost Width="500" Height="500" Name="chart" HorizontalAlignment="Right" /> </Grid> </Window>
4.在cs中包含如下引用
using System.Windows.Forms; using SYstem.Windows.Forms.Integration; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL;
5.創建窗體loaded事件
private void Window_Loaded(object sender, RoutedEventArgs e) { // 創建 GLControl. glc = new GLControl(); // 指定GLControl的Load 和 Paint 事件 glc.Load += new EventHandler(glc_Load); glc.Paint += new System.Windows.Forms.PaintEventHandler(glc_Paint); // 指定這個GLControl作為chart控件的child chart.Child = glc; }
6.添加GLControl的Load和Paint事件
void glc_Load(object sender, EventArgs e) { // 設置背景色 GL.ClearColor(System.Drawing.Color.Chocolate); int w = glc.Width; int h = glc.Height; // 設置初始狀態 GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); GL.Ortho(0, w, 0, h, -1, 1); GL.Viewport(0, 0, w, h); }
void glc_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); GL.MatrixMode(MatrixMode.Modelview); GL.LoadIdentity(); // 畫一個小的黃色三角形 GL.Color3(System.Drawing.Color.Yellow); GL.Begin(BeginMode.Triangles); GL.Vertex2(200, 50); GL.Vertex2(200, 200); GL.Vertex2(100, 50); GL.End(); glc.SwapBuffers(); }
7.編譯運行,完畢。