Skip to content

Instantly share code, notes, and snippets.

@z1nc0r3
Created February 6, 2023 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save z1nc0r3/4fdc091032ddf3fca513ce3d5e22c9d2 to your computer and use it in GitHub Desktop.
Save z1nc0r3/4fdc091032ddf3fca513ce3d5e22c9d2 to your computer and use it in GitHub Desktop.
Bresenham's Line Algorithm
void bresenhamLine(int x0, int y0, int x1, int y1) {
int dx = abs(x1 - x0);
int dy = abs(y1 - y0);
int x, y;
if (dx >= dy) {
int d = 2 * dy - dx;
int ds = 2 * dy;
int dt = 2 * (dy - dx);
if (x0 < x1) {
x = x0;
y = y0;
} else {
x = x1;
y = y1;
x1 = x0;
y1 = y0;
}
putPixel(x, y);
while (x < x1) {
if (d < 0) {
d += ds;
} else {
if (y < y1) {
y++;
d += dt;
} else {
y--;
d += dt;
}
}
x++;
putPixel(x, y);
}
} else {
int d = 2 * dx - dy;
int ds = 2 * dx;
int dt = 2 * (dx - dy);
if (y0 < y1) {
x = x0;
y = y0;
} else {
x = x1;
y = y1;
y1 = y0;
x1 = x0;
}
putPixel(x, y);
while (y < y1) {
if (d < 0) {
d += ds;
} else {
if (x < x1) {
x++;
d += dt;
} else {
x--;
d += dt;
}
}
y++;
putPixel(x, y);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment