利用OpenGL函数,画出n次Bezier曲线
时间: 2024-06-09 11:07:02 浏览: 53
实现n次bezier曲线的绘制
4星 · 用户满意度95%
下面是画出n次Bezier曲线的代码:
```c++
#include <GL/glut.h>
#include <vector>
// 控制点数量
const int kNumControlPoints = 4;
// 控制点坐标
std::vector<float> control_points = { 0.1, 0.1, 0.3, 0.5, 0.6, 0.7, 0.9, 0.3 };
// 递归计算Bezier曲线上的点
void compute_bezier_point(float t, float* point) {
// 初始化中间点为控制点
std::vector<float> mid_points(control_points.begin(), control_points.end());
while (mid_points.size() > 2) {
// 递归计算中间点
std::vector<float> new_mid_points;
for (int i = 0; i < mid_points.size() - 1; i += 2) {
float x = (1 - t) * mid_points[i] + t * mid_points[i + 2];
float y = (1 - t) * mid_points[i + 1] + t * mid_points[i + 3];
new_mid_points.push_back(x);
new_mid_points.push_back(y);
}
mid_points = new_mid_points;
}
// 计算Bezier曲线上的点
point[0] = (1 - t) * mid_points[0] + t * mid_points[2];
point[1] = (1 - t) * mid_points[1] + t * mid_points[3];
}
// 画Bezier曲线
void draw_bezier_curve() {
float point[2];
glBegin(GL_LINE_STRIP);
for (int i = 0; i <= 100; ++i) {
float t = i / 100.0f;
compute_bezier_point(t, point);
glVertex2f(point[0], point[1]);
}
glEnd();
}
// 画控制点
void draw_control_points() {
glPointSize(5);
glColor3f(1, 0, 0);
glBegin(GL_POINTS);
for (int i = 0; i < control_points.size(); i += 2) {
glVertex2f(control_points[i], control_points[i + 1]);
}
glEnd();
}
// 显示回调函数
void display() {
glClear(GL_COLOR_BUFFER_BIT);
draw_bezier_curve();
draw_control_points();
glutSwapBuffers();
}
// 初始化函数
void init() {
glClearColor(1, 1, 1, 1);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 1, 0, 1);
}
// 主函数
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(400, 400);
glutCreateWindow("Bezier Curve");
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}
```
注:以上代码中只画了一个Bezier曲线,如果要画n次Bezier曲线,只需要将control_points数组中的坐标改为n次Bezier曲线的控制点即可。
阅读全文