修改Points列表中的所有项目

时间:2011-06-05 18:54:27

标签: c# list point

    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);
            }
    }

好的,所以我需要我的应用程序在每次左键单击时在表单上绘制点 - 这很好用。所有点都存储在列表pointList中,然后Paint表单逐个绘制它们。

事情是,我需要程序有另一个功能 - 通过用鼠标右键拖动其中一个点来并行移动所有点 - 我已经为此编写了函数,但我无法弄清楚为什么我的代码不能正常工作 - 当我点击右键时,似乎搞砸了整个列表。

我完全没有想法,我会感谢任何提示。

1 个答案:

答案 0 :(得分:1)

在这一行:

diffX = pointList[i].X + (e.X - pointList[i].X);

pointList[i].X条款取消。所以它只是:

diffX = e.X;

您将当前鼠标位置分配给每个点。如果要将所有点移动鼠标移动的距离,但保持它们相对于彼此的位置,则需要记住鼠标的先前位置,以便将其与新位置进行比较。新老鼠位置之间的差异是添加到每个点的正确数量。

所以添加一个字段,如:

Point oldMousePosition;

在按钮发生时初始化它。在每个移动事件中:

pointList[i] = new Point(pointList[i].X + (e.X - oldMousePosition.X),
                         pointList[i].Y + (e.Y - oldMousePosition.Y))