Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move the rectangle with the mouse

I wrote this code:

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

Rectangle moves, but with inversion (it should not be). Can you help?

like image 762
Ticksy Avatar asked Dec 26 '11 16:12

Ticksy


1 Answers

The mathematics in your mouse-move handler for moving the rectangle based on the mouse-movements seems quite off; I think you want something like this:

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

This way, the rectangle's upper left corner will follow the mouse by tracking the delta between the initial mouse-down location and the current mouse location. Note however that each time you re-click and drag, the rectangle will move back to its original location.

If, instead, you want the Rectangle to 'remember' its position across multiple click-and-drag operations (i.e. not to be reinitialized to its initial location on mouse-down) you can do:

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

One other suggestion: There's no need to create your own MovePoint type when there's already the System.Drawing.Point type. Also, in general, try not to create mutable structs.

like image 144
Ani Avatar answered Oct 31 '22 20:10

Ani