将Picturebox重新定位到其默认位置C#

时间:2022-10-13 21:18:20

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?

我正在使用WinForms。在我的WinForms应用程序中,我有一个图片框。我在图片框中有一个图像。此代码使我能够在图片框中移动图像。如何在按钮单击事件中将图像重新定位回其默认位置?

    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 个解决方案

#1


1  

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:

如果您的程序的初始状态是正常的,那么movingPoint = Point.Empty应该可以解决问题。你也应该调用pictureBox1.Invalidate()来重绘图片框:

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

#1


1  

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:

如果您的程序的初始状态是正常的,那么movingPoint = Point.Empty应该可以解决问题。你也应该调用pictureBox1.Invalidate()来重绘图片框:

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