bresenham算法原理:
直接截pdf图了:
C代码如下:
int bresenham(int _x00, int _y00, int _x01, int _y01)
{
int x0[2];
int x1[2];
int dx[2];
int step[2];
int steep;
int err;
int derr;
x0[0] = _x00;
x0[1] = _y00;
x1[0] = _x01;
x1[1] = _y01;
dx[0] = abs(_x01 - _x00);
dx[1] = abs(_y01 - _y00);
steep = dx[1] > dx[0];
err = 0;
derr = dx[1 - steep];
step[0] = ((_x00 < _x01) << 1) - 1;
step[1] = ((_y00 < _y01) << 1) - 1;
for(;x0[steep] != x1[steep];){
if (x0[steep] == x1[steep])
return -1;
x0[steep] += step[steep];
err += derr;
if (err << 1 > dx[steep]) {
x0[1 - steep] += step[1 - steep];
err -= dx[steep];
}
//to do:处理(x0[0],x0[1])
}
}
总共需要考虑4种情况,但是上面的代码了了不到30行,搞定,真佩服代码编写者的数学能力。