Reputation: 53
I have a line C# code with drawing graphichpath, how to get all value every line pixel. not just point (x1,y1) and (x2,y2) point but I want all pixel from (x1,y1) to (x2,y2)
Upvotes: 1
Views: 1430
Reputation: 2204
Here's an algorithm that should give you an estimation of the pixels between your two Points. Note it will not match what is on screen perfectly (which looks antialiased).
public static IEnumerable<Tuple<int,int>> EnumerateLineNoDiagonalSteps(int x0, int y0, int x1, int y1)
{
int dx = Math.Abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
int dy = -Math.Abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
int err = dx + dy, e2;
while(true)
{
yield return Tuple.Create(x0, y0);
if (x0 == x1 && y0 == y1) break;
e2 = 2 * err;
// EITHER horizontal OR vertical step (but not both!)
if (e2 > dy)
{
err += dy;
x0 += sx;
}
else if (e2 < dx)
{ // <--- this "else" makes the difference
err += dx;
y0 += sy;
}
}
}
Replace the Tuple with Point.
For more information, see: http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm or http://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm
Upvotes: 1