0
votes

I'm using WinForms. In my WinForms application I have a picture box. I have a image in the picturebox. This code enables me to move the image around within the picturebox. How do i re-position the image back to its default location on a button click event?

    private Point startingPoint = Point.Empty;
    private Point movingPoint = Point.Empty;
    private bool panning = false;

    private void pictureBox1_MouseDown_1(object sender, MouseEventArgs e)
    {
        if (On_Radio.Checked == true)
        {

            panning = true;
            startingPoint = new Point(e.Location.X - movingPoint.X,
                                      e.Location.Y - movingPoint.Y);
        }

    }



    private void pictureBox1_MouseMove_1(object sender, MouseEventArgs e)
    {
        if (panning)
        {
            movingPoint = new Point(e.Location.X - startingPoint.X,
                                    e.Location.Y - startingPoint.Y);
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        panning = false;
    }

    private void pictureBox1_Paint_1(object sender, PaintEventArgs e)
    {

        e.Graphics.Clear(Color.White);
        e.Graphics.DrawImage(pictureBox1.Image, movingPoint);         
    }
1
Set movingPoint back to Point.Empy and invalidate the PictureBox again. - LarsTech
This didn't set the image back to its default location - taji01
What is the default location supposed to be? - LarsTech
@taji01 if initial state of your program is ok, so movingPoint =Point.Empty should do the trick - Reza Aghaei
@taji01 off-topic but its better to use more clean names for event handlers for example use pictureBox1_MouseMove instead of pictureBox1_MouseMove_1 Also, It's better to use a custom control or custom inherited picturebox to do such panning and draw the image flicker free, You should also consider scroll bars and .... A good sample to start working with GDI+ but you should learn more :) - Reza Aghaei

1 Answers

1
votes

If initial state of your program is ok, so movingPoint = Point.Empty should do the trick. Also you should call pictureBox1.Invalidate() to repaint the picturebox:

private void yourButton_Click(object sender, EventArgs e)
{
    movingPoint = Point.Empty;
    pictureBox1.Invalidate();
}