Created
October 20, 2018 21:36
-
-
Save ske2004/3c0a7494b0c667cc10207347ef2538e9 to your computer and use it in GitHub Desktop.
Bresenham's line algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example program | |
#include <iostream> | |
#include <string> | |
#include <cmath> | |
char buf[32][32]; | |
void clearBuf() | |
{ | |
for (int i = 0; i < 32; i++) | |
for (int j = 0; j < 32; j++) | |
{ | |
buf[i][j] = '.'; | |
} | |
} | |
void drawLine(int y1, int x1, int y2, int x2) { | |
const int deltaX = abs(x2 - x1); | |
const int deltaY = abs(y2 - y1); | |
const int signX = x1 < x2 ? 1 : -1; | |
const int signY = y1 < y2 ? 1 : -1; | |
// | |
int error = deltaX - deltaY; | |
// | |
buf[x2][y2] = '#'; | |
while(x1 != x2 || y1 != y2) | |
{ | |
buf[x1][y1] = '#'; | |
const int error2 = error * 2; | |
// | |
if(error2 > -deltaY) | |
{ | |
error -= deltaY; | |
x1 += signX; | |
} | |
if(error2 < deltaX) | |
{ | |
error += deltaX; | |
y1 += signY; | |
} | |
} | |
} | |
void display() | |
{ | |
for (int i = 0; i < 32; i++) | |
{ | |
for (int j = 0; j < 32; j++) | |
{ | |
std::cout << buf[i][j] << " "; | |
} | |
std::cout << std::endl; | |
} | |
} | |
int main() | |
{ | |
clearBuf(); | |
drawLine(0, 31, 31/2, 0); | |
drawLine(31/2, 0, 31, 31); | |
drawLine(31, 31, 0, 31); | |
drawLine(8, 16, 23, 16); | |
drawLine(8, 16, 31/2, 31); | |
drawLine(23, 16, 32/2, 31); | |
display(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment