在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的等比例縮放。請注意,您需要根據實際情況調整代碼,例如處理圖像加載錯誤或調整縮放后的圖像位置。