【发布时间】:2015-09-06 10:58:56
【问题描述】:
我想要一张图片来填充图片框,但不留下任何空白。因此,当图像的大小未调整为图片框的纵横比时,会切断图像的某些部分以适应它。并在用户调整窗口/图片框大小时进行调整。现有选项Sizemode = Zoom 会留下空白,因为它害怕切断任何图像,Sizemode = StretchImage 会拉伸图像,使其变形。
我能想到的唯一方法是创建一个算法来调整图像大小,保持对比度,并将图像的宽度或长度设置为图片框的宽度或长度,并创建一些运行该算法的运行时循环一帧一次。对于它所做的事情来说,这似乎是一种沉重的表现,而且有点骇人听闻。有更好的选择吗?
编辑: 对于任何路过的人,我实施 Ivan Stoev 的解决方案略有不同:
class ImageHandling
{
public static Rectangle GetScaledRectangle(Image img, Rectangle thumbRect)
{
Size sourceSize = img.Size;
Size targetSize = thumbRect.Size;
float scale = Math.Max((float) targetSize.Width / sourceSize.Width, (float) targetSize.Height / sourceSize.Height);
var rect = new RectangleF();
rect.Width = scale * sourceSize.Width;
rect.Height = scale * sourceSize.Height;
rect.X = (targetSize.Width - rect.Width) / 2;
rect.Y = (targetSize.Height - rect.Height) / 2;
return Rectangle.Round(rect);
}
public static Image GetResizedImage(Image img, Rectangle rect)
{
Bitmap b = new Bitmap(rect.Width, rect.Height);
Graphics g = Graphics.FromImage((Image) b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(img, 0, 0, rect.Width, rect.Height);
g.Dispose();
try
{
return (Image)b.Clone();
}
finally
{
b.Dispose();
b = null;
g = null;
}
}
public Form1()
{
InitializeComponent();
updateMainBackground();
}
void updateMainBackground()
{
Image img = Properties.Resources.BackgroundMain;
Rectangle newRect = ImageHandling.GetScaledRectangle(img, mainBackground.ClientRectangle);
mainBackground.Image = ImageHandling.GetResizedImage(img, newRect);
}
private void Form1_Resize(object sender, EventArgs e)
{
updateMainBackground();
}
}
【问题讨论】:
标签: c# picturebox