使用 OpenGL 使用 C++ 以图形方式表示堆积条形图



我想出了如何制作酒吧,但我的问题在于每个部分底部边缘的位置,我不知道如何使它们完美地堆叠在一起,所以它们中的大多数最终都在另一个顶部,使酒吧看起来不对。这是我的函数:

void StackedBar(void)
{
// Clear the Screen
glClear(GL_COLOR_BUFFER_BIT);
float colors[6][3] = { { 1,0,0 },{ 1,1,0 },{ 0,1,0 },{ 0,1,1 },{ 1,0,1 },{0,0,1} };
float data[6] = { 20,66,42,28,71,23 };
float x = 0, y = 0;
float dy;
glBegin(GL_QUADS);
for (int i = 0; i < 6; i++) {
    glColor3f(colors[i][0], colors[i][1], colors[i][2]);
    dy = data[i];
    glVertex2f(x, y);
    glVertex2f(x + 5, y);
    glVertex2f(x + 5, y + dy);
    glVertex2f(x, y + dy);
    y  = dy;
    //x +=5; incremented x just to see how the pieces are positioned
}
glEnd();
// force execution of GL commands
glFlush();
}

输出:

结果

结果 x 递增 5 只是为了看到碎片的位置

如果你想把条形堆叠在一起,只需在每次迭代中按 dy 递增 y。

for (int i = 0; i < 6; i++) {
    glColor3f(colors[i][0], colors[i][1], colors[i][2]);
    dy = data[i];
    glVertex2f(x, y);
    glVertex2f(x + 5, y);
    glVertex2f(x + 5, y + dy);
    glVertex2f(x, y + dy);
    y += dy;
}

最新更新