序:因為要做個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); |
如果沒有問題,你將看到如下的結果:

|