在C#中,要实现PictureBox的等比例缩放,可以使用以下方法:
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
private Size GetScaledSize(Size originalSize, int maxWidth, int maxHeight)
{
double aspectRatio = (double)originalSize.Width / originalSize.Height;
int newWidth, newHeight;
if (originalSize.Width > originalSize.Height)
{
newWidth = Math.Min(maxWidth, originalSize.Width);
newHeight = (int)(newWidth / aspectRatio);
}
else
{
newHeight = Math.Min(maxHeight, originalSize.Height);
newWidth = (int)(newHeight * aspectRatio);
}
return new Size(newWidth, newHeight);
}
// 加载图像
Image image = Image.FromFile("path_to_your_image");
// 计算新的等比例尺寸
Size newSize = GetScaledSize(image.Size, pictureBox1.Width, pictureBox1.Height);
// 创建一个新的Bitmap,并绘制原始图像到新的Bitmap上
Bitmap scaledImage = new Bitmap(newSize.Width, newSize.Height);
using (Graphics g = Graphics.FromImage(scaledImage))
{
g.DrawImage(image, new Rectangle(0, 0, newSize.Width, newSize.Height));
}
// 将新的等比例图像应用于PictureBox
pictureBox1.Image = scaledImage;
通过这种方式,您可以实现PictureBox的等比例缩放。请注意,您需要根据实际情况调整代码,例如处理图像加载错误或调整缩放后的图像位置。