opengl下的DDA直线算法实现,并用键盘输入直线起点和终点坐标
时间: 2023-05-17 12:07:49 浏览: 129
非常感谢您的提问。下面是基于OpenGL的DDA直线算法实现的代码,可以通过键盘输入直线的起点和终点坐标:
#include <GL/glut.h>
#include <stdio.h>
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
// 获取起点和终点坐标
int x1, y1, x2, y2;
printf("请输入直线的起点和终点坐标:");
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
// 计算直线的斜率
float k = (float)(y2 - y1) / (float)(x2 - x1);
// 计算直线的步长
float dx = 1.0 / fabs(k);
float dy = fabs(k);
// 根据斜率的正负情况选择不同的步长
if (k > 0 && k <= 1) {
float x = x1, y = y1;
glBegin(GL_POINTS);
while (x <= x2) {
glVertex2f(x, y);
x += dx;
y += dy;
}
glEnd();
} else if (k > 1) {
float x = x1, y = y1;
glBegin(GL_POINTS);
while (y <= y2) {
glVertex2f(x, y);
x += dx;
y += dy;
}
glEnd();
} else if (k < 0 && k >= -1) {
float x = x1, y = y1;
glBegin(GL_POINTS);
while (x <= x2) {
glVertex2f(x, y);
x += dx;
y -= dy;
}
glEnd();
} else {
float x = x1, y = y1;
glBegin(GL_POINTS);
while (y >= y2) {
glVertex2f(x, y);
x += dx;
y -= dy;
}
glEnd();
}
glFlush();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("DDA直线算法");
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 500.0, 0.0, 500.0);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
阅读全文