Using Bresenham’s algorithm to create a line

190 Views Asked by At

I'm running into an issue where a line can be drawn if the slope is less than 1, but once the slope is greater, the line still draws a slope of 1. (0,0) to (70,25) (0,0) to (25,70) I'm following some specific pseudocode, which is why I have so many variable assignments.

void drawLine(Point a, Point b){
    int x1 = a.first;
    int x2 = b.first;
    int y1 = a.second;
    int y2 = b.second;
    int dx = x2 - x1;
    int dy = y2 - y1;
    int j = y1;
    int e = dy - dx;

    for(int i = x1; i <= x2-1; i++){
        setPixel(i, j);
        if(e >= 0){
            j++;
            e -= dx;
        }
        e += dy;
    }
}

Here's my set pixel function. It assigns all 3 RGB values of the pixel in the .ppm file to black (0).

void setPixel(int x, int y){
    image[(x+(y*sizex))*3] = 0;
    image[(x+(y*sizex))*3+1] = 0;
    image[(x+(y*sizex))*3+2] = 0;
}
1

There are 1 best solutions below

0
lorro On

As Pepijn Kramer wrote, you need to write this for the distinct cases:

void drawLine(Point a, Point b){
    int x1 = a.first;
    int x2 = b.first;
    int y1 = a.second;
    int y2 = b.second;
    int dx = x2 - x1;
    int dy = y2 - y1;
    int j = y1;
    int e = dy - dx;

    int stepx = dx >= 0 ? 1 : -1;
    int stepy = dy >= 0 ? 1 : -1;

    if (dx >= dy) {
        for(int i = x1; i <= x2-1; i+=stepx) {
            setPixel(i, j);
            if(e >= 0) {
                j+=stepy;
                e -= dx;
            }
            e += dy;
        }
    } else {  /* dy > dx */
        for(int j = y1; j <= y2-1; j+=stepy) {
            setPixel(i, j);
            if(e >= 0) {
                i+=stepx;
                e -= dy;
            }
            e += dx;
        }
    }
}