【c++】Bresenham 栅格画线算法 Wikipedia 版本(图形学)
【c++】Bresenham 栅格画线算法 Wikipedia 版本(图形学)
·
c++ 代码
注: 无需按特定顺序传入两个端点 [x1, y1]
和 [x2, y2]
,即代码覆盖了不同斜率的情况。
void BresenhamLine(int x1, int y1, int x2, int y2) {
int dx = abs(x2 - x1);
int dy = -abs(y2 - y1);
int sx = x1 < x2 ? 1 : -1;
int sy = y1 < y2 ? 1 : -1;
int error = dx + dy;
while (true) {
// === draw img[x1, y1] here ===
if (x1 == x2 && y1 == y2) {
break;
}
if (error * 2 >= dy) {
if (x1 == x2) {
break;
}
error += dy;
x1 += sx;
}
if (error * 2 <= dx) {
if (y1 == y2) {
break;
}
error += dx;
y1 += sy;
}
}
}
来源
Bresenham’s line algorithm - Wikipedia:
https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
更多推荐
所有评论(0)