使用C#的WinForm来实现OpenGL的绘制,将OpenGL内容绘制到WinFrom的背景上。Native方式绘制OpenGL具有最快的速度,可以将内容绘制到WinForm背景、控件等各种Native绘制区域。
通过调用Windows API和OpenGL API来实现,先上代码,马上上传工程文件。
只绘制了背景和一个红叉,在介绍完OpenGL的几种Rander方式后开始讲具体的OpenGL绘图过程!
工程下载地址: http://download.csdn.net/detail/tianyu2202/4351458
原创内容,欢迎转载,转载请注明出处:http://blog.csdn.net/tianyu2202/
/// <summary>初始化 /// </summary> public bool Initialize() { //保存窗体的句柄 windowHandle = this.Handle; //获取窗体的DC deviceContextHandle = GetDC(windowHandle); //初始化绘制窗口的点信息 PIXELFORMATDESCRIPTOR pfd = new PIXELFORMATDESCRIPTOR(); pfd.Init(); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = (byte)32; pfd.cDepthBits = 16; pfd.cStencilBits = 8; pfd.iLayerType = PFD_MAIN_PLANE; //获取点信息 int iPixelformat; if ((iPixelformat = ChoosePixelFormat(deviceContextHandle, pfd)) == 0) return false; //将点信息应用到窗口 if (SetPixelFormat(deviceContextHandle, iPixelformat, pfd) == 0) { return false; } //创建OpenGL渲染器句柄 renderContextHandle = wglCreateContext(deviceContextHandle); //应用渲染器 MakeCurrent(); //初始化OpenGL的状态 glClearColor(0.6f, 0.8f, 0.6f, 1.0f); glClearDepth(1.0f); //初始化完毕 启动Timer开始绘制 timer.Interval = 50; //20帧 timer.Tick += new EventHandler(timer_Tick); timer.Enabled = true; return true; } //执行OpenGL绘制 void timer_Tick(object sender, EventArgs e) { stopwatch.Reset(); stopwatch.Start(); MakeCurrent(); //进行OpenGL的绘制 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, Width, 0.0, Height); glViewport(0, 0, Width, Height); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor4d(1.0, 0.0, 0.0, 1.0); glBegin(GL_LINES); glVertex2i(10, 400); glVertex2i(400, 10); glVertex2i(10, 10); glVertex2i(400, 400); glEnd(); Blit(deviceContextHandle); stopwatch.Stop(); frameTime = stopwatch.Elapsed.TotalMilliseconds; } /// <summary> /// 应用渲染器 /// </summary> public void MakeCurrent() { if (renderContextHandle != IntPtr.Zero) wglMakeCurrent(deviceContextHandle, renderContextHandle); } /// <summary> /// 切换画面(双缓冲) /// </summary> /// <param name="hdc">绘图DC的句柄.</param> public void Blit(IntPtr hdc) { if (deviceContextHandle != IntPtr.Zero || windowHandle != IntPtr.Zero) { SwapBuffers(deviceContextHandle); } }