How to zoom picturebox along with graphics

安稳与你 提交于 2020-01-03 06:37:18

问题


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:


回答1:


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..



来源:https://stackoverflow.com/questions/33011251/how-to-zoom-picturebox-along-with-graphics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!