WPF+OpenTK+OpenGL简单使用
OpenTK的简单使用
OpenTK是对OpenGL的封装,可以在C#中使用,实现了跨平台,当然也可以用在WinForm和WPF中。
第一步:声明
首先创建一个WPF程序,引用程序集
1.System.Windows.Forms
2.WindowsFormsIntegration
添加OpenTK的两个引用
1.OpenTK
2.OpenTK.GLControl
在cs文件中声明为:
1.using System.Windows.Forms;
2.using System.Windows.Forms.Integration;
3.using OpenTK;
4.using OpenTK.Graphics;
5.using OpenTK.Graphics.OpenGL;
第二步:XAML窗体界面
<Grid>
<WindowsFormsHost Initialized="WindowsFormsHost_Initialized" Name="Host" Margin="0,0,140,0"/>
<Slider Orientation="Vertical" Value="1" Minimum="0" Maximum="1" Name="Red" ValueChanged="Slider_ValueChanged" Margin="0,0,56,0" RenderTransformOrigin="2.174,0.498" HorizontalAlignment="Right" Width="23"/>
<Slider Orientation="Vertical" Value="0" Minimum="0" Maximum="1" Name="Green" ValueChanged="Slider_ValueChanged" Margin="0,0,26,0" HorizontalAlignment="Right" Width="25"/>
<Slider Orientation="Vertical" Value="0" Minimum="0" Maximum="1" Name="Blue" ValueChanged="Slider_ValueChanged" Margin="0,0,4,0" HorizontalAlignment="Right" Width="22"/>
</Grid>
这里写了一个WindowsFormsHost控件,该控件它允许在 WPF 页上托管 Windows 窗体控件,注册了初始化属性Initialized为WindowsFormsHost_Initialized方法。
写了三个滑动块用来控制背景颜色R,G,B,注册了值变化的事件Slider_ValueChanged。
第三步:WindowsFormsHost初始化
WindowsFormsHost初始化方法:
private void WindowsFormsHost_Initialized(object sender, EventArgs e)
{
var flags = GraphicsContextFlags.Default;
#if USE_ANGLE
flags = GraphicsContextFlags.Embedded;
#endif
glControl = new GLControl(new GraphicsMode(32, 24), 2, 0, flags);//创建GLControl控件
glControl.MakeCurrent();
glControl.Paint += GLControl_Paint;
glControl.Dock = DockStyle.Fill;//注册重绘控件的方法
(sender as WindowsFormsHost).Child = glControl;//将控件放在WindowsFormsHost控件中
}
重绘控件的方法:
private void GLControl_Paint(object sender, PaintEventArgs e)
{
GL.ClearColor(
(float)Red.Value,
(float)Green.Value,
(float)Blue.Value,
1);
GL.Clear(
ClearBufferMask.ColorBufferBit |
ClearBufferMask.DepthBufferBit |
ClearBufferMask.StencilBufferBit);//清空视图
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
if (glControl!= null)
{
float halfWidth = (float)(this.glControl.Width / 2);
float halfHeight = (float)(this.glControl.Height / 2);
GL.Ortho(-halfWidth, halfWidth, halfHeight, -halfHeight, 1000, -1000);
GL.Viewport(this.glControl.Size);//设置视角
}
GL.Begin(PrimitiveType.Triangles);//绘制三角形
GL.Vertex3(0, 50, 0); // 三角形的顶点
GL.Vertex3(0, 0, 0);
GL.Vertex3(50, 0, 0);
GL.End();
GL.Finish();
glControl.SwapBuffers();
}
第四步:滑动块改变背景颜色
拖动滑动块重新绘制背景颜色
private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (this.glControl!=null)
{
this.glControl.Invalidate();//重新绘制
}
}
效果图:
这样就实现了WPF使用OpenTK,后续使用OpenTK画一个柱体,并实现摄像机的移动。
代码地址:https://download.csdn.net/download/qq_33930691/16781294