用 SharpGL 画一个三角形

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值