用鼠标移动矩形

时间:2011-12-26 16:23:18

标签: c# winforms selection move

我写了这段代码:

private struct MovePoint
    {
        public int X;
        public int Y;
    }
private void Image_MouseDown(object sender, MouseEventArgs e)
    {
        FirstPoint = new MovePoint();
        FirstPoint.X = e.X;
        FirstPoint.Y = e.Y;
    }

    private void Image_MouseMove(object sender, MouseEventArgs e)
    {
        if(e.Button == MouseButtons.Left)
        {
            if(FirstPoint.X > e.X)
            {
                Rectangle.X = FirstPoint.X - e.X;
                //Rectangle.Width -= FirstPoint.X - e.X;
            } else
            {
                Rectangle.X = FirstPoint.X + e.X;
                //Rectangle.Width += FirstPoint.X + e.X;
            }

            if(FirstPoint.Y > e.Y)
            {
                Rectangle.Y = FirstPoint.Y - e.Y;
                //Rectangle.Height -= FirstPoint.Y - e.Y;
            } else
            {
                Rectangle.Y = FirstPoint.Y + e.Y;
                //Rectangle.Height += FirstPoint.Y + e.Y;
            }

            Image.Invalidate();
        }
    }
private void Image_Paint(object sender, PaintEventArgs e)
    {
        if(Pen != null) e.Graphics.DrawRectangle(Pen, Rectangle);
    }

矩形移动,但有反转(不应该)。你能帮忙吗?

1 个答案:

答案 0 :(得分:5)

基于鼠标移动移动矩形的鼠标移动处理程序中的数学似乎相当不合适;我想你想要这样的东西:

private void Image_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        int initialX = 0, initialY = 0; // for example.

        Rectangle.X = (e.X - FirstPoint.X) + initialX; 
        Rectangle.Y = (e.Y - FirstPoint.Y) + initialY;

        Image.Invalidate();
    }
}

这样,矩形的左上角将跟踪鼠标,方法是跟踪初始鼠标按下位置和当前鼠标位置之间的差值。但请注意,每次重新单击并拖动时,矩形都将移回原始位置。

相反,如果你希望Rectangle在多次点击并拖动操作中“记住”它的位置(即不要在鼠标按下时重新初始化到它的初始位置),你可以这样做:

private void Image_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        // Increment rectangle-location by mouse-location delta.
        Rectangle.X += e.X - FirstPoint.X; 
        Rectangle.Y += e.Y - FirstPoint.Y; 

        // Re-calibrate on each move operation.
        FirstPoint = new MovePoint { X = e.X, Y = e.Y };

        Image.Invalidate();
    }
}

另一个建议:当已经有MovePoint类型时,无需创建自己的System.Drawing.Point类型。另外,一般来说,尽量不要创建可变结构。