1

我正在尝试制作一个色板工具,在其中你给它 n 种颜色,它会制作一个 n 边形,这些颜色在中心合并。

到目前为止,它只是制作了一个 n-gon(没有指定颜色,它现在随机生成它们)。

然而,颜色不会在中心合并,而是在单个顶点处合并。

有什么解决办法吗?

#include <GLFW/glfw3.h>
#include <iostream>
#include <cmath>
float randfloat(){
  float r = ((float)(rand() % 10))/10;
  return r;
}
int main() {
  int side_count;
  std::cout<<"Type the no. of sides: "<<std::endl;
  std::cin>>side_count;
  srand(time(NULL));
  std::cout<<randfloat()<<std::endl;
  std::cout<<randfloat()<<std::endl;
  float rs[side_count];
  float gs[side_count];
  float bs[side_count];
  for (int i=0;i<side_count;i++)
  {
    rs[i] = randfloat();
    gs[i] = randfloat();
    bs[i] = randfloat();
  }
  GLFWwindow* window;
  if (!glfwInit())
    return 1;
  window = glfwCreateWindow(800, 800, "Window", NULL, NULL);
  if (!window) {
    glfwTerminate();
    return 1;
  }
  glfwMakeContextCurrent(window);
  if(glewInit()!=GLEW_OK)
    std::cout<<"Error"<<std::endl;

  while(!glfwWindowShouldClose(window)) {
    glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(0.11f,0.15f,0.17f,1.0f);
    glBegin(GL_POLYGON);
      //glColor3f(1.0f,0.0f,0.0f);glVertex3f(-0.5f,0.0f,0.0f);
      for(int i=0; i<side_count;i++)
      {
        float r = rs[i];
        float g = gs[i];
        float b = bs[i];
        float x = 0.5f * sin(2.0*M_PI*i/side_count);
        float y = 0.5f * cos(2.0*M_PI*i/side_count);
        glColor3f(r,g,b);glVertex2f(x,y);
      }
    glEnd();
    glfwSwapBuffers(window);
    glfwPollEvents();
  }
  glfwTerminate();
  return 0;
}
4

1 回答 1

2

您所要做的就是GL_POLYGON在圆形的中心向基元添加一个新点:

glBegin(GL_TRIANGLE_FAN);

glColor3f(0.5f, 0.5f, 0.5f);
glVertex2f(0, 0);

for(int i=0; i <= side_count; i++)
{
    float r = rs[i % side_count];
    float g = gs[i % side_count];
    float b = bs[i % side_count];
    float x = 0.5f * sin(2.0*M_PI*i/side_count);
    float y = 0.5f * cos(2.0*M_PI*i/side_count);
    glColor3f(r, g, b);
    glVertex2f(x, y);
}

glEnd();

请注意,您必须定义中心点的颜色。在代码片段中,我选择了 (0.5, 0.5, 0.5)。
代替GL_POLYGON,GL_TRIANGLE_FAN 也可以使用。

于 2019-05-09T20:21:19.473 回答