Microsoft 對 OpenGL 缺乏原生支援,但可透過第三方封裝庫在 C# 中使用 OpenGL。本文介紹兩個知名庫並提供 CSopenGL 實作範例。
#region Using directives
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using CSOpenGL;
#endregion
namespace opentest
{
partial class Form1 : System.Windows.Forms.Form
{
private GLView view;
public Form1()
{
InitializeComponent();
view = new GLView();
view.Parent = this;
view.CreateControl();
view.Dock = DockStyle.Fill;
view._OnPaint = new Painter();
}
private void Form1_Load(object sender, EventArgs e) { }
}
public class Painter : GLViewPainter
{
public Painter() { }
public override void Paint(GLView view)
{
// 設定視口與投影矩陣
glViewport(0, 0, view.Width, view.Height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, 1.0f, 0.1f, 100.0f);
glShadeModel(GL_SMOOTH);
// 深度測試與清除顏色
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
// 繪製立方體 (可切換註解繪製金字塔或球體)
// drawPyramid();
// drawSphere();
drawCube();
glFlush();
}
private void drawPyramid() { /* ... 省略頂點繪製代碼 ... */ }
private void drawCube() { /* ... 省略立方體繪製代碼,含透明混合效果 ... */ }
private void drawSphere() { /* ... 省略球體繪製代碼,含光源設定 ... */ }
}
}
#region Using directives
using System;
using System.Collections.Generic;
using System.Windows.Forms;
#endregion
namespace opentest
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.EnableRTLMirroring();
Application.Run(new Form1());
}
}
}
CSOpenGL 命名空間。GLView 控制項並設定 Dock = DockStyle.Fill 填滿視窗。GLViewPainter 衍生類別,覆寫 Paint 方法撰寫 OpenGL 繪圖指令。Painter 實例指派給 view._OnPaint。透過 CSopenGL 或 CsGL,C# 開發者能輕鬆導入 OpenGL 3D 繪圖功能,適合科學視覺化、遊戲原型或教學專案。