C#openGL画立方体
时间: 2023-07-12 11:04:40 浏览: 123
OPENGL.rar_opengl 立方体
下面是一个使用C#和OpenGL画立方体的示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using Tao.OpenGl;
using Tao.FreeGlut;
namespace OpenGLTutorial
{
class Program : Form
{
static void Main(string[] args)
{
Application.Run(new Program());
}
public Program()
{
this.Load += new EventHandler(Form_Load);
this.Paint += new PaintEventHandler(Form_Paint);
this.Resize += new EventHandler(Form_Resize);
}
private void Form_Load(object sender, EventArgs e)
{
Glut.glutInit();
Glut.glutInitDisplayMode(Glut.GLUT_RGBA | Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH);
Gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
Gl.glViewport(0, 0, this.Width, this.Height);
Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glLoadIdentity();
Glu.gluPerspective(45, (double)this.Width / (double)this.Height, 0.1, 200);
Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glLoadIdentity();
Gl.glEnable(Gl.GL_DEPTH_TEST);
}
private void Form_Resize(object sender, EventArgs e)
{
Gl.glViewport(0, 0, this.Width, this.Height);
Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glLoadIdentity();
Glu.gluPerspective(45, (double)this.Width / (double)this.Height, 0.1, 200);
Gl.glMatrixMode(Gl.GL_MODELVIEW);
}
private void Form_Paint(object sender, PaintEventArgs e)
{
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT);
Gl.glLoadIdentity();
Gl.glTranslatef(0.0f, 0.0f, -6.0f);
Gl.glBegin(Gl.GL_QUADS);
// Front Face
Gl.glColor3f(1.0f, 0.0f, 0.0f);
Gl.glVertex3f(-1.0f, -1.0f, 1.0f);
Gl.glVertex3f( 1.0f, -1.0f, 1.0f);
Gl.glVertex3f( 1.0f, 1.0f, 1.0f);
Gl.glVertex3f(-1.0f, 1.0f, 1.0f);
// Back Face
Gl.glColor3f(0.0f, 1.0f, 0.0f);
Gl.glVertex3f(-1.0f, -1.0f, -1.0f);
Gl.glVertex3f(-1.0f, 1.0f, -1.0f);
Gl.glVertex3f( 1.0f, 1.0f, -1.0f);
Gl.glVertex3f( 1.0f, -1.0f, -1.0f);
// Top Face
Gl.glColor3f(0.0f, 0.0f, 1.0f);
Gl.glVertex3f(-1.0f, 1.0f, -1.0f);
Gl.glVertex3f(-1.0f, 1.0f, 1.0f);
Gl.glVertex3f( 1.0f, 1.0f, 1.0f);
Gl.glVertex3f( 1.0f, 1.0f, -1.0f);
// Bottom Face
Gl.glColor3f(1.0f, 1.0f, 0.0f);
Gl.glVertex3f(-1.0f, -1.0f, -1.0f);
Gl.glVertex3f( 1.0f, -1.0f, -1.0f);
Gl.glVertex3f( 1.0f, -1.0f, 1.0f);
Gl.glVertex3f(-1.0f, -1.0f, 1.0f);
// Right face
Gl.glColor3f(1.0f, 0.0f, 1.0f);
Gl.glVertex3f( 1.0f, -1.0f, -1.0f);
Gl.glVertex3f( 1.0f, 1.0f, -1.0f);
Gl.glVertex3f( 1.0f, 1.0f, 1.0f);
Gl.glVertex3f( 1.0f, -1.0f, 1.0f);
// Left Face
Gl.glColor3f(0.0f, 1.0f, 1.0f);
Gl.glVertex3f(-1.0f, -1.0f, -1.0f);
Gl.glVertex3f(-1.0f, -1.0f, 1.0f);
Gl.glVertex3f(-1.0f, 1.0f, 1.0f);
Gl.glVertex3f(-1.0f, 1.0f, -1.0f);
Gl.glEnd();
Gl.glFlush();
Glut.glutSwapBuffers();
}
}
}
```
在上面的代码中,我们使用了Tao.OpenGl和Tao.FreeGlut库来进行OpenGL编程。在构造函数中,我们注册了窗体的Load、Resize和Paint事件。在Load事件处理函数中,我们设置了OpenGL的视口、投影矩阵和模型矩阵,并启用了深度测试。在Resize事件处理函数中,我们根据窗体大小重新设置了投影矩阵。在Paint事件处理函数中,我们使用glBegin和glEnd函数来绘制立方体,并设置了每个面的颜色。最后,我们使用glFlush和glutSwapBuffers函数将绘制结果显示出来。
阅读全文