序:因为要做个2d地图编辑器,决定采用MFC,但是GDI不是很熟,google下终于完成基本MFC下的OpenGL
1.首先建个MFC单文档
2.加入外部库:opengl32.lib glu32.lib 在XXView.cpp加入头文件 gl.h, glu.h
3.在XXView.h加入如下代码:
5 |
BOOL InitOpenGL(); # 初始化opengl |
6 |
BOOL SetPixelFormat(); # 设置像素格式 |
7 |
void RenderScene(); # 绘制 |
4.首先重载OnCreate消息
01 |
int CXXView::OnCreate(LPCREATESTRUCT lpCreateStrcut) |
03 |
if (CView::OnCreate(lpCreateStruct) == -1) |
5.现在完成初始化OpenGL的代码
01 |
BOOL CXXView::InitializeOpenGL() |
04 |
m_pDC = new CClientDC( this ); |
07 |
MessageBox( "错误: 无法创建设备上下文" ); |
12 |
if (!SetPixelFormat()) |
16 |
m_hRC = wglCreateContext(m_pDC->GetSafeHdc()); |
19 |
MessageBox( "错误: 无法创建绘制环境" ); |
23 |
if (wglMakeCurrent(m_pDC->GetSafeHdc(), m_hRC) == FALSE) |
25 |
MessageBox( "错误: 无法作为当前RC" ); |
29 |
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); |
31 |
glEnable(GL_DEPTH_TEST); |
6. 如上5中提到的设置像素格式
01 |
BOOL CXXView::SetPixelFormat() |
04 |
PIXELFORMATDESCRIPTOR pfd= |
06 |
sizeof (PIXELFORMATDESCRIPTOR), |
08 |
PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL| |
09 |
PFD_DOUBLEBUFFER|PFD_TYPE_RGBA, |
24 |
int m_nPixelFormat = ChoosePixelFormat(m_pDC->GetSafeHdc(), &pfd); |
25 |
if (m_nPixelFormat == 0) |
30 |
if (SetPixelFormat(m_pDC->GetSafeHdc(), m_nPixelFormat, &pfd) == FALSE) |
7.当然是视图,并且包括窗口改变时重新设置视图
01 |
void CXXView::OnSize( UINT nType, int cx, int cy) |
03 |
CView::OnSize(nType, cx, cy); |
06 |
if ( 0 >= cx || 0 >= cy) |
09 |
glViewport(0, 0, cx, cy); |
10 |
GLdouble aspect_ratio = (GLdouble)cx / (GLdouble)cy; |
12 |
glMatrixMode(GL_PROJECTION); |
14 |
gluPerspective(45.0f, aspect_ratio, 0.01f, 200.0f); |
15 |
glMatrixMode(GL_MODELVIEW); |
8.既然基本都完成,我们在哪里绘制我们图像呢?--》OnDraw
01 |
void CXXView::OnDraw(CDC* pDC) |
03 |
CMfcOpenglDoc* pDoc = GetDocument(); |
09 |
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); |
13 |
SwapBuffers(pDC->GetSafeHdc()); |
9.开始绘制图像,这里就绘制一个方块
01 |
void CXXView::RenderScene( GLvoid ) |
04 |
glTranslatef(0.0f, 0.0f, -6.0f); |
05 |
glBegin(GL_TRIANGLES); |
07 |
glColor3f(255.0f,0.0f,0.0f); |
08 |
glVertex3f(-1.0f, 1.0f, 0.0f); |
09 |
glColor3f(0.0f,255.0f,0.0f); |
10 |
glVertex3f( 1.0f, 1.0f, 0.0f); |
11 |
glColor3f(0.0f,0.0f,255.0f); |
12 |
lVertex3f( 1.0f,-1.0f, 0.0f); |
13 |
glColor3f(255.255f,255.0f,255.0f); |
14 |
glVertex3f(-1.0f,-1.0f, 0.0f); |
10.退出程序的时候记得要销毁创建的DC, RC
01 |
void CXXView::OnDestroy() |
06 |
if (wglGetCurrentContext()!=NULL) |
09 |
wglDeleteContext(m_hRC); |
如果没有问题,你将看到如下的结果:
|