用鼠标移动矩形

5
我写了这段代码:
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);
    }

矩形移动了,但是出现了反向(这不应该发生)。你能帮忙解决吗?


你从未给矩形指定宽度或高度。 - Hans Passant
@Hans:这似乎只是一个片段。如果矩形没有初始宽度和高度,那么OP就不可能看到它移动(尽管不正确)。 :) - Ani
@HansPassant:给定了宽度和高度,但我还没有发布这段代码。 - Ticksy
1个回答

6
你鼠标移动处理程序中的数学计算似乎有误,我认为你需要像这样做:

鉴于您的鼠标移动处理程序是基于鼠标移动来移动矩形的,因此其中的数学计算似乎不太准确。我认为你可能需要像下面这样:

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

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

如果您希望矩形在多个单击和拖动操作之间“记住”其位置(即不要在鼠标按下时重新初始化到其初始位置),则可以执行以下操作:

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

另外一个建议:当已经有System.Drawing.Point类型时,就没有必要再创建自己的MovePoint类型了。此外,一般情况下,应尽量避免创建可变结构体。


非常感谢!特别是在回答的第二部分中(思考如何通过重置位置来修复此错误)。 - Ticksy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接