我实现了我在网上找到的这个算法,它可以很好地绘制水平线和所有对角线的一半。但是当对角线通过“中途”标记变为垂直时,它不会更新 y 并且只会绘制斜率较小的线。它确实将它一直绘制到 x2,但绘制了一条倾斜到不同 y2 坐标的线。如果你尝试画一条垂直线,什么也画不出来。任何人都可以找到错误吗?
void init()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 500.0, 0.0, 500.0);
}
void midPoint(int x1, int y1, int x2, int y2)
{
if (x1 > x2)
{
midPoint(x2, y2, x1, y1);
return;
}
int slope;
int dx, dy, d, x, y;
dx = x2 - x1;
dy = y2 - y1;
d = dx - 2 * dy;
y = y1;
if (dy < 0) {
slope = -1;
dy = -dy;
}
else {
slope = 1;
}
for (x = x1; x < x2; x++) {
glBegin(GL_POINTS);
glVertex2f(x, y);
if (d <= 0) {
d += 2 * dx - 2 * dy;
y += slope;
}
else {
d += -2 * dy;
}
glEnd();
}
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
midPoint(10, 10, 110, 210);
glColor3f(0.0, 1.0, 0.0);
midPoint(10, 10, 210, 110);
glColor3f(1.0, 1.0, 0.0);
midPoint(210, 10, 10, 110);
glFlush();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(50, 50);
glutInitWindowSize(500, 500);
glutCreateWindow("Bresenham\'s midpoint line algorithm");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}