1 #include <windows.h> 2 #include <math.h> 3 #include <gl/GL.h> 4 #include <gl/glut.h> 5 int SCREEN_HEIGHT = 480; 6 int NUMPOINTS = 0; 7 class Point 8 { 9 public: 10 float x, y; 11 void setxy(float x2, float y2) 12 { 13 x = x2; 14 y = y2; 15 } 16 Point operator&(const Point & rPoint) 17 { 18 x = rPoint.x; 19 y = rPoint.y; 20 return * this; 21 } 22 }; 23 Point abc[4]; 24 void myInit() 25 { 26 glClearColor(0.0,0.0,0.0,0.0); 27 glColor3f(1.0f, 0.0, 0.0); 28 glPointSize(4.0); 29 glMatrixMode(GL_PROJECTION); 30 glLoadIdentity(); 31 gluOrtho2D(0.0, 640, 0.0, 480.0); 32 } 33 void drawDot(Point pt) 34 { 35 glBegin(GL_POINTS); 36 glVertex2f(pt.x, pt.y); 37 glEnd(); 38 glFlush(); 39 } 40 void drawLine(Point p1, Point p2) 41 { 42 glBegin(GL_LINES); 43 glVertex2f(p1.x, p1.y); 44 glVertex2f(p2.x, p2.y); 45 glEnd(); 46 glFlush(); 47 } 48 //四个控制点的贝塞尔曲线 即三次Bezier曲线 49 Point drawBezier(Point A, Point B, Point C, Point D,double t) 50 { 51 Point P; 52 double a1 = pow((1-t),3); 53 double a2 = pow((1-t),2)*3*t; 54 double a3 = 3*t*t*(1-t); 55 double a4 = t*t*t; 56 57 P.x = a1*A.x+a2*B.x+a3*C.x+a4*D.x; 58 P.y = a1*A.y+a2*B.y+a3*C.y+a4*D.y; 59 return P; 60 } 61 void myMouse(int button, int state, int x, int y) 62 { 63 if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) 64 { 65 abc[NUMPOINTS].setxy((float)x, (float)(SCREEN_HEIGHT - y)); 66 NUMPOINTS++; 67 if (NUMPOINTS == 4) 68 { 69 glColor3f(1.0, 0.0, 1.0); 70 drawDot(abc[0]); 71 drawDot(abc[1]); 72 drawDot(abc[2]); 73 drawDot(abc[3]); 74 glColor3f(1.0, 1.0, 0.0); 75 drawLine(abc[0], abc[1]); 76 drawLine(abc[1], abc[2]); 77 drawLine(abc[2], abc[3]); 78 glColor3f(0.0, 1.0, 1.0); 79 Point POld = abc[0]; 80 for (double t = 0.0; t<=1.0;t+=0.1) 81 { 82 Point P = drawBezier(abc[0], abc[1], abc[2], abc[3], t); 83 drawLine(POld, P); 84 POld = P; 85 } 86 glColor3f(1.0, 0.0, 0.0); 87 NUMPOINTS = 0; 88 } 89 } 90 } 91 void myDisplay() 92 { 93 glClear(GL_COLOR_BUFFER_BIT); 94 glFlush(); 95 } 96 int main(int argc, char * agrv[]) 97 { 98 glutInit(&argc, agrv); 99 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); 100 glutInitWindowSize(640, 480); 101 glutInitWindowPosition(100, 150); 102 glutCreateWindow("Bezier Curve"); 103 glutMouseFunc(myMouse); 104 glutDisplayFunc(myDisplay); 105 myInit(); 106 glutMainLoop(); 107 return 0; 108 }
保留代码自己慢慢看~