List<Point> pointList;
public int pickedIndexRight = -1;
public int diffX = 0;
public int diffY = 0;
public Form1()
{
InitializeComponent();
pointList = new List<Point>();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
Point myPoint = new Point(e.X, e.Y);
if (e.Button == MouseButtons.Left)
{
if (pickedIndex == -1)
{
if (pointList.Contains(myPoint) == false)
{
pointList.Add(myPoint);
}
}
}
else if (e.Button == MouseButtons.Right)
{
//if right click near a point then pickedIndexRight is index of that point in list
pickedIndexRight = pointList.FindIndex(delegate(Point point) { return Distance(point, myPoint) < 10; });
}
Invalidate();
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right && pickedIndexRight != -1)
{
for (int i = 0; i < pointList.Count - 1; i++)//(int i = pointList.Count - 1; i > 0; i--)
{
diffX = pointList[i].X + (e.X - pointList[i].X);
diffY = pointList[i].Y + (e.Y - pointList[i].Y);
pointList[i] = new Point(diffX, diffY);
Invalidate();
}
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
pickedIndexRight = -1;
Invalidate();
}
private double Distance(Point p1, Point p2) //calculate distance between two points
{
double d = Math.Sqrt((p2.X - p1.X) * (p2.X - p1.X) + (p2.Y - p1.Y) * (p2.Y - p1.Y));
return d;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
foreach (Point myPoint in pointList)
{
e.Graphics.DrawRectangle(Pens.Black, myPoint.X, myPoint.Y, 1, 1);
}
}
Ok, so I need my app to draw points on a form with every left click - that works just fine. All the points are stored in a list pointList and then the Paint form draws them each one by one.
The thing is, i need the program to have another functionality - moving all points in parallel by dragging one of the points with the right mouse button - I already wrote the function for that but I can't figure out why my code doesn't work prop开发者_JS百科erly - it seems to screw up the entire list when i right click.
I'm all out of ideas, I'd be thankful for any hints.
In this line:
diffX = pointList[i].X + (e.X - pointList[i].X);
The pointList[i].X
terms cancel out. So it's just:
diffX = e.X;
You're assigning the current mouse position to every point. If you want to move all the points by the distance that the mouse has moved, but keep their positions relative to each other, you need to remember the previous position of the mouse, so you can compare it with the new position. The difference between new and old mouse positions is the correct amount to add to each point.
So add a field such as:
Point oldMousePosition;
And initialise it when the button-down occurs. In each move event:
pointList[i] = new Point(pointList[i].X + (e.X - oldMousePosition.X),
pointList[i].Y + (e.Y - oldMousePosition.Y))
精彩评论