3,882
社区成员




//------------Bresenham画线算法---------------------
//--------------by D_Viking-------------------------
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<GL/glut.h>
/*Bresenham line-drawing procedure for |m|<1.0 */
void init(void){
glClearColor(1.0, 1.0, 1.0, 0.0);//Set display-window color to white.
glMatrixMode(GL_PROJECTION);//Set projection parameters.
gluOrtho2D(0.0, 550.0, 0.0, 550.0);
}
void setPixel(GLint x, GLint y){
glClear(GL_COLOR_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
glColor3f(1, 0, 0);//Set line segment color to green.
glVertex2i(x, y);
glPointSize(9);//绘制前设置点的大小和颜色
glEnd();
glFlush();
}
void lineBres(){
int x0, y0, xEnd, yEnd;
//scanf_s("%d", &x0); scanf_s("%d", &xEnd); scanf_s("%d", &y0); scanf_s("%d", ¥d);
x0 = 60; y0 = 300; xEnd = 100; yEnd = 400;
glClear(GL_COLOR_BUFFER_BIT);//Clear display window.
glColor3f(1, 0, 0);//Set line segment color to green.
int dx = (int)fabs((float)xEnd - x0), dy = (int)fabs((float)yEnd - y0);
int p = 2 * dy - dx;
int twoDy = 2 * dy, twoDyMinusDx = 2 * (dy - dx);
int x, y;
/*Determine which endpoint to use as start position.*/
if (x0 > xEnd){
x = xEnd;
y = yEnd;
xEnd = x0;
}
else
{
x = x0;
y = y0;
}
setPixel(x, y);
while (x < xEnd){
x++;
if (p < 0)
p += twoDy;
else
{
y++;
p += twoDyMinusDx;
}
setPixel(x, y);
}
}
void main(int argc, char** argv){
glutInit(&argc, argv);//Initialize GLUT.
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);//Set display mode.
glutInitWindowPosition(50, 100);//Set top-left display-window position.
glutInitWindowSize(400, 300);//Set display-window width and height.
glutCreateWindow("Bresenham画线算法");//Create display window.
init();//Execute initialization procedure.
glutDisplayFunc(lineBres);//Send graphics to display window.
glutMainLoop();//Display everything and wait.
}