放大和缩小图片框

时间:2014-05-11 11:06:18

标签: c# zoom picturebox windows-forms-designer

我有一个带有pictureBox的表单,显示图像。我还有2个按钮 - 放大和缩小。当图像放大时,我希望能够将其拖动到旁边,以便能够看到图像中的其他部分。 问题是,当我单击放大按钮时,它工作正常,但拖动不会移动图片框内的图像(我可以拖动图像,但是当我释放鼠标按钮时它总是返回到相同的位置) ,当我缩小图像时不居中并仅显示已放大的图像的一部分,它还会更改图片框的大小并更改其在表单上的位置。

我的代码:

    private double ZOOM_INTERVAL = 0.25;
    private double currentZoom = 1.0;

    //zoom out from product image
    private void ZoomOutBtn_Click(object sender, EventArgs e)
    {
        if (currentZoom > 0.5)
        {
            currentZoom -= ZOOM_INTERVAL;
            ResizeImage();
        }
    }

    //zoom in to product image
    private void ZoomInBtn_Click(object sender, EventArgs e)
    {
        currentZoom += ZOOM_INTERVAL;
        ResizeImage();
    }

    private void ResizeImage()
    {
        Bitmap img = initialImage;
        if (img != null)
        {
            Bitmap bmp = new Bitmap(img, Convert.ToInt32(initialImage.Width * currentZoom), Convert.ToInt32(initialImage.Height * currentZoom));
            Graphics g = Graphics.FromImage(bmp);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            pictureBox1.Image = bmp;
            g.Dispose();
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            mouseDownLoc = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
              Point currentMousePos = e.Location;
              int distanceX = currentMousePos.X - mouseDownLoc.X;
              int distanceY = currentMousePos.Y - mouseDownLoc.Y;
              int newX = pictureBox1.Location.X + distanceX;
              int newY = pictureBox1.Location.Y + distanceY;
              if(newX + pictureBox1.Image.Width < pictureBox1.Image.Width && pictureBox1.Image.Width + newX > panel1.Width)

                    pictureBox1.Location = new Point(newX, pictureBox1.Location.Y);

              if(newY + pictureBox1.Image.Height < pictureBox1.Image.Height && pictureBox1.Image.Height + newY > panel1.Height)

                    pictureBox1.Location = new Point(pictureBox1.Location.X, newY);
        }
    }

提前致谢。

0 个答案:

没有答案
相关问题