Develop a program to draw a line using Bresenham’s line-drawing technique

Develop a program to draw a line using Bresenham’s line-drawing technique

Program:-

#include <GL/glut.h>

// Define the points for the line
int x0 = 50, y0 = 50, x1 = 200, y1 = 200;

void bresenhamLine(int x0, int y0, int x1, int y1) {
    int dx = x1 - x0;
    int dy = y1 - y0;
    int d = 2*dy - dx;
    int incrE = 2*dy;
    int incrNE = 2*(dy - dx);
    int x = x0;
    int y = y0;

    glClear(GL_COLOR_BUFFER_BIT);
    glBegin(GL_POINTS);

    glVertex2i(x, y);
    while (x < x1) {
        if (d <= 0) {
            d += incrE;
            x++;
        } else {
            d += incrNE;
            x++;
            y++;
        }
        glVertex2i(x, y);
    }

    glEnd();
    glFlush();
}

void display() {
    bresenhamLine(x0, y0, x1, y1);
}

void init() {
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glColor3f(1.0, 1.0, 1.0);
    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(0.0, 300.0, 0.0, 300.0);
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("Bresenham's Line Drawing");
    init();
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *