OpenGL绘制圆弧/圆/饼图 2
- //rorger,2011
- //contact me: jhcyd112@163.com
- //in this new version, we can both draw a arc/circle/pi with color filled or not.
- #include "windows.h"
- #include "glut.h"
- #include "math.h"
- #define width 640
- #define height 480
- void drawArc(double x,double y,double start_angle,double end_angle,double delta_angle,double radius,bool fill)
- {
- if (fill)
- {
- glBegin(GL_TRIANGLE_FAN);
- }
- else
- {
- glBegin(GL_LINE_STRIP);
- }
- for (double i=start_angle;i<=end_angle;i+=delta_angle)
- {
- double vx=x+radius * cos(i);
- double vy=y+radius*sin(i);
- glVertex2d(vx,vy);
- }
- glEnd();
- }
- void drawCircle(double x, double y, double radius,bool fill)
- {
- double pi=acos(-1.0);
- drawArc(x,y,0,2*pi,pi/180,radius,fill);
- }
- void drawPie(double x,double y,double start_angle,double end_angle,double delta_angle,double radius,bool fill)
- {
- drawArc(x,y,start_angle,end_angle,delta_angle,radius,fill);
- if (fill)
- {
- glBegin(GL_TRIANGLE_FAN);
- }
- else
- {
- glBegin(GL_LINES);
- }
- glVertex2d(x,y);
- glVertex2d(x+radius*cos(start_angle),y+radius*sin(start_angle));
- if (!fill)
- {
- glVertex2d(x,y);
- }
- glVertex2d(x+radius*cos(end_angle),y+radius*sin(end_angle));
- glEnd();
- }
- void myDisplay(void) // plot the sinc function, using world coordinates
- {
- double pi=acos(-1.0);
- glClear(GL_COLOR_BUFFER_BIT);
- //画笛卡尔坐标系
- glColor3f(1.0,0.0,0.0);
- glBegin(GL_LINES);
- glVertex2d(-width/2.0,0);
- glVertex2d(width/2.0,0);
- glEnd();
- glBegin(GL_LINES);
- glVertex2d(0,height/2.0);
- glVertex2d(0,-height/2.0);
- glEnd();
- glColor3f(1.0,1.0,0.0);
- //draw a circle
- drawCircle(0,0,100,false);
- //draw two arcs
- drawArc(0,0,0,pi/2.0,pi/180,200,false);
- drawArc(0,0,pi,3*pi/2.0,pi/180,200,true);
- glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- glColor4f(0.1,1.0f,0.0,0.5);
- //draw two pies
- drawPie(0,0,5*pi/4.0,7*pi/4.0,pi/180.0,200,false);
- drawPie(0,0,pi/4.0,3*pi/4.0,pi/180.0,200,false);
- glDisable(GL_BLEND);
- glFlush();
- }
- void myInit(void)
- {
- glClearColor(0.0, 0.0, 0.0, 0.0);
- glColor3f(0.0f, 0.0f, 1.0f);
- glPointSize(4.0);
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- gluOrtho2D(-width/2.0,width/2.0,-height/2.0,height/2.0);
- glLineWidth(2.0);
- }
- void main(int argc, char** argv)
- {
- glutInit(&argc, argv);
- glutInitDisplayMode(GLUT_SINGLE |GLUT_RGBA);
- glutInitWindowSize(width,height);
- glutInitWindowPosition(100,150);
- glutCreateWindow("LineInterSectoin");
- glutDisplayFunc(myDisplay);
- myInit( );
- glutMainLoop( );
- }
Note:你可以设置参数fill为true或者false来使图形得到填充或这空填充
其实还有一个不完善的地方,那就是没有自定义边缘颜色和填充颜色。不过相信这已经不是一个问题了。