我刚刚尝试运行Bresenham函数,该函数从2个顶点绘制一条线,但是仅出现GLUT的白色屏幕,根本没有线。这是我的源代码,有人可以帮助我吗?
#include <math.h>
#include <windows.h>
#include <GL/glut.h>
#include <GL/gl.h>
void init(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, 500.0, 0.0, 500.0);
}
void Bresenham(int x1, int y1, int x2, int y2) {
int Dx = abs(x2 - x1);
int Dy = abs(y2 - y1);
int p = 2 * Dy - Dx;
int c1 = 2 * Dy;
int c2 = 2 * (Dy - Dx);
int x = x1;
int y = y1;
int x_unit = 1, y_unit = 1;
glVertex2d(x, y);
while (x != x2) {
if (p<0) p += c1;
else {
p += c2;
y += y_unit;
}
x += x_unit;
glVertex2d(x, y);
}
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
Bresenham(50, 150, 300, 200);
glEnd();
glFlush();
}
int main(int iArgc, char** cppArgv) {
glutInit(&iArgc, cppArgv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(600, 600);
glutInitWindowPosition(50, 50);
glutCreateWindow("Line");
init();
int x1=50, y1=150, x2=300, y2=200;
glutDisplayFunc(display);
glutMainLoop();
return EXIT_SUCCESS;
}
答案 0 :(得分:1)
确保您的背景颜色与您的绘图颜色不匹配。有点难以看清白色:)
用红色画线在我的机器上有效:
#include <GL/glut.h>
void Bresenham(int x1, int y1, int x2, int y2)
{
int Dx = abs(x2 - x1);
int Dy = abs(y2 - y1);
int p = 2 * Dy - Dx;
int c1 = 2 * Dy;
int c2 = 2 * (Dy - Dx);
int x = x1;
int y = y1;
int x_unit = 1, y_unit = 1;
glVertex2d(x, y);
while (x != x2)
{
if (p<0)
p += c1;
else
{
p += c2;
y += y_unit;
}
x += x_unit;
glVertex2d(x, y);
}
}
void display(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 500.0, 0.0, 500.0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glBegin(GL_POLYGON);
glColor3ub( 255, 0, 0 );
Bresenham(50, 150, 300, 200);
glEnd();
glutSwapBuffers();
}
int main(int argc, char** argv )
{
glutInit( &argc, argv );
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(600, 600);
glutCreateWindow("Line");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}