#include <iostream>
#include <cstring>
// #define DEBUG
using namespace std;
int canvas[100][100];
void innerSwap(int & x, int & y) {
int temp = x;
x = y;
y = temp;
}
int sign(int x) {
if (x > 0) {
return 1;
}
else if (x == 0) {
return 0;
}
return -1;
}
int abs(int x) {
return x > 0 ? x : -x;
}
void init(void) {
memset(canvas, sizeof(canvas), 0);
}
void setPixel(int x, int y, int color) {
canvas[y][x] = color;
}
void printPrompt(int fromx, int fromy, int tox, int toy) {
printf("A line from : (%d, %d) to (%d, %d) \n", fromx, fromy, tox, toy);
}
// src point (fromx, from y)
// dst point (tox, toy)
void general_bresenham(int fromx, int fromy, int tox, int toy, int color) {
// Print prompt
printPrompt(fromx, fromy, tox, toy);
int signx = sign(tox - fromx);
int signy = sign(toy - fromy);
int dy = toy - fromy;
int dx = tox - fromx;
bool hasExchanged = false;
#ifdef DEBUG
cout << endl << "abs(dx) = " << abs(dx) << " abs(dy) = " << abs(dy) << "\n\n";
#endif
// Judge the growing direction
// Slope K : abs(K) > 1
if (abs(dy) > abs(dx)) {
innerSwap(dx, dy);
hasExchanged = true;
}
// Initial bias
int e = 2*dy - dx;
// Calculate each points' position and paint on canvas
int x = fromx;
int y = fromy;
// Paint ( dx + 1 ) times
for (int i = 0 ; i <= dx ; ++i) {
setPixel(x, y, color);
// abs(K) > 1
// Y dirextion self increment with signy
// X direction depend on the value of e
if (hasExchanged) {
y = y + signy;
if (e >= 0) {
x = x + 1;
// Update e
e = e + 2*dy - 2*dx;
}
else {
e = e + 2*dy;
}
}
else {
x = x + signx;
if (e >= 0) {
y = y + 1;
// Update e
e = e + 2*dy - 2*dx;
}
else {
e = e + 2*dy;
}
}
}
}
// Print canvas from (0, 0) to (lenx, leny)
void showCanvas(int lenx, int leny) {
for (int i = lenx ; i >=0 ; --i) {
for (int j = 0; j <= leny ; ++j) {
cout << canvas[i][j] << " ";
}
cout << endl;
}
for (int i = 0 ; i < leny ; ++i) {
cout << "--";
}
cout << "> X axis" << endl;
}
int main(void) {
init();
general_bresenham(0, 0, 2, 5, 1);
showCanvas(8, 8);
return 0;
}
输出: