I want to be able to select part of an image via two Points (p1,p2). My problem is that I want to use the same loop regardless in which order they are.
right now I have this:
for (int x = p1.X; x != p2.X; x += Math.Sign(p2.X - p1.X))
{
for (int y = p1.Y; y != p2.Y; y += Math.Sign(p2.Y - p1.Y))
{
MessageBox.Show(String.Format("{0} {1}", x, y));
}
}
With that loop I don't get all of the numbers: e.g. from 1/1 to 3/3 only gones till 2/2.
I some how need to loop through both loops one more time, but since I don't know which way I'm actually looping (decreasing or increasing) I can't just add/ subtract one from the loop.
any help would be ap开发者_如何学Cpreciated!
You can just loop from the lowest X to the highest X, and then do the same for Y.
for (int x = Math.Min(p1.X, p2.X); x <= Math.Max(p1.X, p2.X); x++){
for (int y = Math.Min(p1.Y, p2.Y); y <= Math.Max(p1.Y, p2.Y); y++){
MessageBox.Show(String.Format("{0} {1}", x, y));
}
}
This will not walk down from [3,3] to [1,1]. If you actually care about the direction, this approach won't work.
Point p1 = new Point(1, 1);
Point p2 = new Point(3, 3);
int dx = Math.Sign(p2.X - p1.X);
int dy = Math.Sign(p2.Y - p1.Y);
for (int x = p1.X; x != p2.X + dx; x += dx)
{
for (int y = p1.Y; y != p2.Y + dy; y += dy)
{
Console.WriteLine("{0} {1}", x, y);
}
}
精彩评论