所有点都被一条线穿过
我需要找到一条线上的所有点。我尝试了 Bresenham 算法,但它不适用于以下情况:
(0, 0)
.-----------+-----------+-----------.
|...........| | |
|...........| | |
|.....XXXX..| | |
|........XXXX | |
|...........XXXXX | |
+-----------+---XXXX----+-----------+
| |......XXXXX|...........|
| |..........XXXX.........|
| |...........|.XXXXX.....|
| |...........|...........|
| |...........|...........|
`-----------+-----------+-----------´
(2, 1)
X
是实际行,.
是 Bresenham 算法返回的内容,请注意该行与 ( 1, 0)
但未标记。
如何有效地找到一条线经过的所有像素?我不需要这种抗锯齿功能,所以我认为吴的算法有点矫枉过正。线条端点位于像素中间。
参考我的算法是:
int dx = System.Math.Abs(x0 - x1);
int dy = System.Math.Abs(y0 - y1);
int sx = x0 < x1 ? 1 : -1;
int sy = y0 < y1 ? 1 : -1;
int err = dx - dy;
int lx = x0;
int ly = y0;
for(int i = 0; true; i++)
{
Mark(x0, y0);
if(x0 == x1 && y0 == y1)
break;
int e2 = err * 2;
if(e2 > -dy)
{
err -= dy;
x0 += sx;
}
if(e2 < dx)
{
err += dx;
y0 += sy;
}
}
I need to find all points that are on a line. I tried Bresenham's algorithm but it doesn't work on the following case:
(0, 0)
.-----------+-----------+-----------.
|...........| | |
|...........| | |
|.....XXXX..| | |
|........XXXX | |
|...........XXXXX | |
+-----------+---XXXX----+-----------+
| |......XXXXX|...........|
| |..........XXXX.........|
| |...........|.XXXXX.....|
| |...........|...........|
| |...........|...........|
`-----------+-----------+-----------´
(2, 1)
X
is the actual line, .
is what Bresenham's algorithm returns, notice the line crosses (1, 0)
but it is not marked.
How can I find all the pixels a line goes through efficiently? I don't need this anti-aliased so I think Wu's algorithm is an overkill. The line endpoints are in middle of the pixels.
To reference the algorithm I have is:
int dx = System.Math.Abs(x0 - x1);
int dy = System.Math.Abs(y0 - y1);
int sx = x0 < x1 ? 1 : -1;
int sy = y0 < y1 ? 1 : -1;
int err = dx - dy;
int lx = x0;
int ly = y0;
for(int i = 0; true; i++)
{
Mark(x0, y0);
if(x0 == x1 && y0 == y1)
break;
int e2 = err * 2;
if(e2 > -dy)
{
err -= dy;
x0 += sx;
}
if(e2 < dx)
{
err += dx;
y0 += sy;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,只需实现明显简单的算法:从线的一端开始,找到它穿过起始方块的哪一侧,跳到相应的相邻方块......等等。步行直到到达终点广场。
以整数实现它的最简单方法是切换到超像素精度:只需将所有值乘以常数因子即可。当您发现没有足够的整数范围来充分乘以它时,困难的部分就开始了......我不知道您的情况是否属于这种情况。
Well, just implement the obvious straightforward algorithm: start from one end of the line, find which side of the starting square it crosses, jump to the corresponding adjacent square... and so on. Walk until you reach the finish square.
The simplest way to implement it in integers would be to switch to superpixel precision: just multiply everything by a constant factor. The difficult part begins when you discover that you don't have enough integer range to multiply it sufficiently... I don't know whether this is the case in your case.