mfc带纹理紫砂壶代码
时间: 2023-07-09 14:43:14 浏览: 111
以下是一个简单的 MFC 带纹理紫砂壶代码示例:
首先,在资源管理器中导入纹理文件,比如命名为 "Zisha.bmp"。
然后,在 MFC 应用程序的 View 类中添加如下代码:
```
// 首先,在头文件中添加以下代码
#include <gl/gl.h> // OpenGL 头文件
#include <gl/glu.h> // OpenGL 实用工具库头文件
#include "bmp.h" // 用于读取 BMP 文件的头文件
// 在 CView 类的 OnDraw 函数中添加如下代码
void CView::OnDraw(CDC* pDC)
{
// 获取视口大小
CRect rect;
GetClientRect(&rect);
int nWidth = rect.Width();
int nHeight = rect.Height();
// 设置 OpenGL 环境
static HGLRC hRC = NULL;
static HDC hDC = NULL;
if (hRC == NULL) {
hDC = ::GetDC(m_hWnd);
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), 1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0
};
int nPixelFormat = ::ChoosePixelFormat(hDC, &pfd);
::SetPixelFormat(hDC, nPixelFormat, &pfd);
hRC = ::wglCreateContext(hDC);
::wglMakeCurrent(hDC, hRC);
::glViewport(0, 0, nWidth, nHeight);
::glMatrixMode(GL_PROJECTION);
::glLoadIdentity();
::gluPerspective(60.0, (double)nWidth / (double)nHeight, 0.1, 100.0);
::glMatrixMode(GL_MODELVIEW);
::glLoadIdentity();
::glEnable(GL_TEXTURE_2D);
::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);
}
// 加载纹理
static GLuint texture = 0;
if (texture == 0) {
CBmp bmp;
bmp.Load(_T("Zisha.bmp")); // 读取 BMP 文件
::glGenTextures(1, &texture);
::glBindTexture(GL_TEXTURE_2D, texture);
::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, bmp.GetWidth(), bmp.GetHeight(), 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, bmp.GetData());
}
// 绘制紫砂壶
::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
::glLoadIdentity();
::glTranslatef(0.0f, 0.0f, -5.0f);
::glRotatef(30.0f, 1.0f, 0.0f, 0.0f);
::glRotatef(30.0f, 0.0f, 1.0f, 0.0f);
::glBindTexture(GL_TEXTURE_2D, texture);
::glBegin(GL_QUADS);
::glTexCoord2f(0.0f, 0.0f); ::glVertex3f(-1.0f, -1.0f, 0.0f);
::glTexCoord2f(1.0f, 0.0f); ::glVertex3f(1.0f, -1.0f, 0.0f);
::glTexCoord2f(1.0f, 1.0f); ::glVertex3f(1.0f, 1.0f, 0.0f);
::glTexCoord2f(0.0f, 1.0f); ::glVertex3f(-1.0f, 1.0f, 0.0f);
::glEnd();
// 刷新 OpenGL 窗口
::SwapBuffers(hDC);
}
```
最后,在 MFC 应用程序的 InitInstance 函数中添加如下代码:
```
BOOL CMyApp::InitInstance()
{
...
AfxEnableControlContainer();
CFrameWnd* pFrame = new CFrameWnd;
m_pMainWnd = pFrame;
pFrame->Create(NULL, _T("MFC OpenGL Texture Demo"));
CView* pView = new CView;
pFrame->SetWindowText(_T("MFC OpenGL Texture Demo"));
pFrame->SetWindowPos(NULL, 0, 0, 640, 480, SWP_NOMOVE | SWP_NOZORDER);
pFrame->SetMenu(NULL);
pFrame->CreateStatusBar();
pFrame->ShowWindow(SW_SHOW);
pFrame->UpdateWindow();
pFrame->SetActiveView(pView);
pView->OnInitialUpdate();
...
return TRUE;
}
```
运行程序后,应该就可以看到带纹理的紫砂壶了。注意,这只是一个简单的示例,实际情况可能需要更复杂的代码和纹理处理。
阅读全文