1. 来源
三次贝塞尔曲线就是依据四个位置任意的点坐标绘制出的一条光滑曲线
2. 公式
3. 实现
#include <iostream>
#include <math.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include <vector>
//#include <pair> using namespace std; //points保存四个点
vector<pair<GLfloat, GLfloat> > points;
//设置两个bool变量来记录是否已经画出四个点之间的直线,以及相关贝塞尔曲线
bool line = false;
bool curve = false; //画直线
void drawLine() {
glColor3f(1.0f, , );
glPointSize(1.0);
for (int i = ; i <= ; i ++) {
glBegin(GL_LINES);
glVertex2f(points[i].first, points[i].second);
glVertex2f(points[i+].first, points[i+].second);
glEnd();
}
} //贝塞尔曲线
void drawCurve() {
glColor3f(, 1.0f, );
glPointSize(1.0);
for (GLfloat t = ; t <= 1.0; t += 0.001) {
GLfloat x = points[].first*pow(1.0f-t, ) + *points[].first*t*pow(1.0f-t, ) + *points[].first*t*t*(1.0f-t) + points[].first*pow(t, );
GLfloat y = points[].second*pow(1.0f-t, ) + *points[].second*t*pow(1.0f-t, ) + *points[].second*t*t*(1.0f-t) + points[].second*pow(t, );
glBegin(GL_POINTS);
glVertex2f(x, y);
glEnd();
}
} //初始化函数
void myInit() {
glClearColor(, , , );
glColor3f(1.0f, , );
glPointSize(5.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluOrtho2D(0.0, , 0.0, );
} void myDisplay() {
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
} //对于鼠标点击的响应函数
void myMouse(int button, int state, int x, int y)
{
//按下鼠标左键
if(state==GLUT_DOWN)
{
//画4个点
if (points.size() < ) {
glBegin(GL_POINTS);
glVertex2i(x, - y);
glEnd();
points.push_back(make_pair(GLfloat(x), GLfloat( - y)));
}
//若已经画好四个点,则开始画点连成的线段\曲线
else if (points.size() == ) {
//线段
if (line == false) {
drawLine();
line = true;
}
//曲线
else if (line == true && curve == false) {
drawCurve();
curve = true;
}
//清空
else if (line == true && curve == true) {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, , );
glPointSize(5.0);
line = false;
curve = false;
while(!points.empty()) {
points.pop_back();
}
}
}
glFlush();
}
} int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowPosition(, );
glutInitWindowSize(, );
glutCreateWindow("Bezier-curve"); myInit();
glutDisplayFunc (myDisplay);
glutMouseFunc(myMouse);
glutMainLoop();
return ;
}
4. 延伸
一次、二次、五次贝赛尔曲线以及贝塞尔曲线的升阶,具体:
https://zh.wikipedia.org/zh-cn/%E8%B2%9D%E8%8C%B2%E6%9B%B2%E7%B7%9A