1.概要
2.代码
2.1 控件代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SharpGL;
namespace WinFormsApp5
{
public partial class OpenGLControl : UserControl
{
private OpenGL gl;
public OpenGLControl()
{
InitializeComponent();
this.DoubleBuffered = true;
// 初始化OpenGL
gl = new OpenGL();
// 设置视口(在控件大小改变时更新)
this.Resize += OpenGLControl_Resize;
}
private void OpenGLControl_Resize(object sender, EventArgs e)
{
// 更新OpenGL视口大小
gl.Viewport(0, 0, this.Width, this.Height);
// 设置投影矩阵(例如正交投影)
gl.MatrixMode(OpenGL.GL_PROJECTION);
gl.LoadIdentity();
//gluPerspective(45.0f, (float)this.Width / (float)this.Height, 0.1f, 100.0f); // 使用gluPerspective需要GLU库,但SharpGL默认不包含,这里仅作示例
// 或者使用正交投影
// gl.Ortho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
gl.Ortho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
// 设置模型视图矩阵
gl.MatrixMode(OpenGL.GL_MODELVIEW);
gl.LoadIdentity();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// 清除屏幕和深度缓冲区
gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);
// 启用顶点数组(可选,但通常用于更复杂的场景)
// gl.EnableClientState(OpenGL.GL_VERTEX_ARRAY);
// 开始绘制
gl.Begin(OpenGL.GL_TRIANGLES); // 使用GL_TRIANGLES来绘制三角形
// 指定三角形的顶点(在3D空间中)
gl.Vertex(0.0f, 0.5f, 0.0f); // 顶点1
gl.Vertex(-0.5f, -0.5f, 0.0f); // 顶点2
gl.Vertex(0.5f, -0.5f, 0.0f); // 顶点3
// 结束绘制
gl.End();
// 禁用顶点数组(如果之前启用了)
// gl.DisableClientState(OpenGL.GL_VERTEX_ARRAY);
// 刷新绘制到屏幕
gl.Flush();
}
}
}
2.2 主窗口代码
using System.Diagnostics;
namespace WinFormsApp5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OpenGLControl openGLControl = new OpenGLControl();
Controls.Add(openGLControl);
}
}
}
3.运行结果
4.附加依赖下载
SharpGL