简体   繁体   中英

How to zoom picturebox along with graphics

I want to zoom picture box along with graphics.

this will Zoom the only image part not the graphics part.

public Image PictureBoxZoom(Image imgP, Size size)
{
    Bitmap bm = new Bitmap(imgP, Convert.ToInt32(imgP.Width * size.Width), Convert.ToInt32(imgP.Height * size.Height));
    Graphics grap = Graphics.FromImage(bm);
    grap.InterpolationMode = InterpolationMode.HighQualityBicubic;
    return bm;
}

private void zoomSlider_Scroll(object sender, EventArgs e)
{
    if (zoomSlider.Value > 0 && img != null)
    {
        pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
        pictureBox1.Image = null;
        pictureBox1.Image = PictureBoxZoom(img, new Size(zoomSlider.Value, zoomSlider.Value));
    }
}

the source of image is:

img = Image.FromStream(openFileDialog1.OpenFile());

Picture is zooming but when we draw the rectangle outside image then it's not zooming along with image.

See image:

在此处输入图片说明

You can do this (rather) easily by scaling the e.Graphics object in the Paint event.. See here for an example !

So to work with you code you probably should add this to the Paint event:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
  Graphics g = e.Graphics;

  g.ScaleTransform(zoom, zoom);

  // now do your drawing..
  // here just a demo ellipse and a line..
  Rectangle rect = panel1.ClientRectangle;
  g.DrawEllipse(Pens.Firebrick, rect);
  using (Pen pen = new Pen(Color.DarkBlue, 4f)) g.DrawLine(pen, 22, 22, 88, 88);
}

To calculate the zoom factor you need to do a little calculation.

Usually you would not create a zoomed Image but leave that job to the PictureBox with a SizeMode=Zoom .

Then you could write:

float zoom =  1f * pictureBox1.ClientSize.Width / pictureBox1.Image.Width;

To center the image one usually moves the PictureBox inside a Panel . And to allow scrolling one sets the Panel to Autocroll=true;

But since you are creating a zoomed Image you should keep track of the current zoom by some other means.

Note:

But as you use PictureBoxSizeMode.CenterImage maybe your problem is not with the zooming after all?? If your issue really is the placement, not the size of the drawn graphics you need to do a e.Graphics.TranslateTransform to move it to the right spot..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM