OpenGL利用visual studio c++绘制一个实心的圆,要求圆分成若干个扇形,每个扇形颜色不同
时间: 2024-06-09 18:01:06 浏览: 192
以下是OpenGL利用visual studio c绘制一个实心的圆,圆分成若干个扇形,每个扇形颜色不同的代码实现:
```c++
#include <iostream>
#include <GL/glut.h>
#include <cmath>
using namespace std;
const int WIDTH = 640;
const int HEIGHT = 480;
void init()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, WIDTH, 0, HEIGHT);
}
void drawSector(float cx, float cy, float r, float start_angle, float end_angle, float red, float green, float blue)
{
glColor3f(red, green, blue);
glBegin(GL_TRIANGLE_FAN);
glVertex2f(cx, cy);
for (float angle = start_angle; angle <= end_angle; angle += 0.01)
{
float x = cx + r * cos(angle * 3.14 / 180);
float y = cy + r * sin(angle * 3.14 / 180);
glVertex2f(x, y);
}
glEnd();
}
void drawCircle(float cx, float cy, float r, int num_sectors)
{
float angle_per_sector = 360.0 / num_sectors;
float start_angle = 0.0;
float end_angle = angle_per_sector;
for (int i = 0; i < num_sectors; i++)
{
if (i % 2 == 0)
{
drawSector(cx, cy, r, start_angle, end_angle, 1.0, 0.0, 0.0);
}
else
{
drawSector(cx, cy, r, start_angle, end_angle, 0.0, 0.0, 1.0);
}
start_angle = end_angle;
end_angle += angle_per_sector;
}
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
drawCircle(WIDTH / 2, HEIGHT / 2, 200, 12);
glFlush();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(WIDTH, HEIGHT);
glutInitWindowPosition(100, 100);
glutCreateWindow("OpenGL Circle");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
```
代码中,我们定义了一个`drawSector`函数,用于绘制一个扇形,需要指定圆心坐标、半径、起始角度、终止角度和颜色。然后定义了一个`drawCircle`函数,用于绘制一个圆,需要指定圆心坐标、半径和分成的扇形数目,每个扇形颜色不同,通过调用`drawSector`函数实现。最后在`display`函数中调用`drawCircle`函数绘制圆。
阅读全文