调整PictureBox中的图像大小,直到它与原始图像的大小相同

时间:2022-12-22 21:21:21

I want an image within a PictureBox that will adjust automatically depending on the size of the window but, not larger than the original image. While PictureBoxSizeMode.Zoom almost does this, when the PictureBox is larger than the image it causes the image to pixelate. I'm currently executing this code on resize:

我想要一个PictureBox中的图像,它将根据窗口的大小自动调整,但不大于原始图像。虽然PictureBoxSizeMode.Zoom几乎这样做,但当PictureBox大于图像时,它会使图像像素化。我目前正在调整大小时执行此代码:

if (pBox.Height * pBox.Height < pBox.Image.Width * pBox.Image.Height) pBox.SizeMode = PictureBoxSizeMode.Zoom;
else pBox.SizeMode = PictureBoxSizeMode.CenterImage;

While this works most of the time, occasionally the image won't revert back to zoom:

虽然这在大多数情况下都有效,但偶尔图像也不会恢复变焦:

调整PictureBox中的图像大小,直到它与原始图像的大小相同 调整PictureBox中的图像大小,直到它与原始图像的大小相同

Any better way to go about this?

有什么更好的办法吗?

2 个解决方案

#1


1  

How about setting the maximum size to the image size:

如何将最大尺寸设置为图像尺寸:

pictureBox1.MaximumSize = pictureBox1.Image.Size;

In Combination with :

结合:

pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

#2


0  

You should use "if (pBox.Width * pBox.Height < pBox.Image.Width * pBox.Image.Height)" if() Statement. Both dimensions of pBox is taken as height, might cause some problem. Check it

你应该使用“if(pBox.Width * pBox.Height

#1


1  

How about setting the maximum size to the image size:

如何将最大尺寸设置为图像尺寸:

pictureBox1.MaximumSize = pictureBox1.Image.Size;

In Combination with :

结合:

pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

#2


0  

You should use "if (pBox.Width * pBox.Height < pBox.Image.Width * pBox.Image.Height)" if() Statement. Both dimensions of pBox is taken as height, might cause some problem. Check it

你应该使用“if(pBox.Width * pBox.Height