gpt4 book ai didi

opengl - 想要一个OpenGL 2D示例(VC++,绘制一个矩形)

转载 作者:行者123 更新时间:2023-12-04 13:34:45 24 4
gpt4 key购买 nike

我想创建一个高性能的2D程序。

我正在使用VC++ 2008。假设我已经创建了主窗口。我想要的是在主窗口的工作区中绘制一个红色矩形(左上角:10,20,右下角:200、300),就像FillRect()API所做的一样,但使用的是OpenGL。

void InitOpenGL(HWND hwnd)
{
.... // What should I do?
// Only for 2D drawing, and the (0,0) should be the top left point.
}

// the function below will be called in the WM_PAINT handler
void DrawRectWithOpenGL(RECT* pRect)
{
.... // What should I do?
}

EDIT1:OpenGL是否具有2D绘图API或类似Direct2D/DirectWrite的库?

最佳答案

我强烈建议您看一些OpenGL教程(http://nehe.gamedev.net/是一个很好的网站,它会告诉您所有您需要知道的内容),但是假设您在代码中正确设置了OpenGL,则可以在您的DrawRectWithOpenGL函数(我不是C++程序员,但我认为我的代码适合C++):

void DrawRectWithOpenGL(RECT* pRect)
{
glPushMatrix(); //Make sure our transformations don't affect any other transformations in other code
glTranslatef(pRect->x, pRect->y, 0.0f); //Translate rectangle to its assigned x and y position
//Put other transformations here
glBegin(GL_QUADS); //We want to draw a quad, i.e. shape with four sides
glColor3f(1, 0, 0); //Set the colour to red
glVertex2f(0, 0); //Draw the four corners of the rectangle
glVertex2f(0, pRect->h);
glVertex2f(pRect->w, pRect->h);
glVertex2f(pRect->w, 0);
glEnd();
glPopMatrix();
}

OpenGL没有2D绘图API,但通过忽略Z轴(或仅使用Z轴来确保以正确的深度绘制 Sprite )即可轻松地完成2D事情,例如,您可以在前景,因为设置了背景的深度,因此它位于前景的后面)。希望这可以帮助。一定要花一些时间看一些教程,这些都将变得很清楚。

编辑:
要为2D绘图设置OpenGL,您需要设置一个正投影(我链接到的教程使用了透视投影,很遗憾没有提及)。这是我的一些代码执行此操作的示例(创建窗口后,该代码应位于InitOpenGL函数中的某个位置):
glClearColor(0.0, 0.0, 0.0, 0.0);  //Set the cleared screen colour to black
glViewport(0, 0, screenwidth, screenheight); //This sets up the viewport so that the coordinates (0, 0) are at the top left of the window

//Set up the orthographic projection so that coordinates (0, 0) are in the top left
//and the minimum and maximum depth is -10 and 10. To enable depth just put in
//glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, screenwidth, screenheight, 0, -10, 10);

//Back to the modelview so we can draw stuff
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); //Clear the screen and depth buffer

这就是排序的初始化。您应该能够使用100和200之类的值,并使它们正确显示在屏幕上,即坐标以像素为单位。

为了处理窗口大小的变化,您要做的是找到窗口的大小(使用外部库。我不确定您可以在OpenGL中完成此操作,尽管GLUT中的glutGet(GLUT_WINDOW_WIDTH)和glutGet(GLUT_WINDOW_HEIGHT)可能有效,但我尚未对其进行测试),然后使用更新后的窗口大小再次调用glViewport和glOrtho。

同样,您必须使用一个外部库来准确地确定窗口大小何时更改。我不确定您可以使用什么,但是如果您碰巧正在使用SDL,则可能会对其进行一些事件处理(如果glutGet无法正常工作,则可以返回屏幕的宽度和高度)。

我希望这有帮助!

关于opengl - 想要一个OpenGL 2D示例(VC++,绘制一个矩形),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5877728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com