先计算出各顶点(外顶点和内顶点),可以确定每个三角形和中间的正五边形,分别涂色即可。
代码:
#include <windows.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <bits/stdc++.h>
#include <stdlib.h>
using namespace std;
const double PI = acos(-1.0);
struct Point{
GLfloat x, y;
Point operator - (const Point &b) const {
return Point{x-b.x, y-b.y};
}
Point rot(Point p, double angle){
Point v = (*this)-p;
double c = cos(angle), s = sin(angle);
return Point{p.x+v.x*c-v.y*s, p.y+v.x*s+v.y*c};
}
};
void init(){
glClearColor(0.0, 0.0, 0.0, 0.0);
glColor3f(1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
}
double a = 0.8;
Point p[5] = {
Point{0, a},
Point{-a*cos(18*PI/180), a*sin(18*PI/180)},
Point{-a*cos(54*PI/180), -a*sin(54*PI/180)},
Point{a*cos(54*PI/180), -a*sin(54*PI/180)},
Point{a*cos(18*PI/180), a*sin(18*PI/180)}
};
void Star(int n){
glColor3f(1, 0, 1);
Point pp[5];
for(int i=0; i<n; i++){
Point p0 = Point{(p[i].x+p[(i+1)%5].x)/2, (p[i].y+p[(i+1)%5].y)/2};
double rato = sin(36*PI/180)/cos(36*PI/180);
rato = 1 - rato*rato;
pp[i] = Point{p0.x*rato, p0.y*rato};
}
for(int i=0; i<5; i++){
switch(i){
case (0): glColor3f(1, 1, 0); break;
case (1): glColor3f(1, 0, 0); break;
case (2): glColor3f(0, 0, 1); break;
case (3): glColor3f(0, 1, 0.75); break;
case (4): glColor3f(1, 0, 1); break;
}
glBegin(GL_POLYGON);
glVertex2f(p[i].x, p[i].y);
glVertex2f(pp[(i+4)%5].x, pp[(i+4)%5].y);
glVertex2f(pp[i].x, pp[i].y);
glEnd();
}
glColor3f(0.5, 0.9, 1);
glBegin(GL_POLYGON);
for(int i=0; i<5; i++)
glVertex2f(pp[i].x, pp[i].y);
glEnd();
}
void display(){
glClear(GL_COLOR_BUFFER_BIT);
Star(5);
glFlush();
}
int main(int argc, char **argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(0, 0);
glutCreateWindow("STAR");
glutDisplayFunc(display);
init();
glutMainLoop();
}
效果