如何将图片框的“居中”背景图像绘制到面板?

时间:2012-07-02 19:13:52

标签: c# winforms picturebox

我很好地提供了来自Alex M的代码,用于将背景图像绘制到面板但是意识到如果PictureBox的{​​{1}}具有其中心图像属性设置,则绘制的图像将被拉伸但没有居中。到目前为止我有这段代码:

BackgroundImage

这会将背景图像绘制到面板,但如果private void panel1_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawImage(pictureBox1.BackgroundImage, new Rectangle(pictureBox1.Location, pictureBox1.Size)); } 的背景图像属性设置为CENTER,则它不会在矩形的中心绘制图像,而是拉伸图像以适合矩形。

我找到的唯一可能的解决方案是here,但我无法理解它。

1 个答案:

答案 0 :(得分:1)

图像被拉伸的原因是因为DrawImage的第二个参数指定了绘制图像的位置和大小,并且您指定了图片框的整个区域,而不是图像的区域本身。

如果你想让它居中,试试这样的事情:

private void panel1_Paint(object sender, PaintEventArgs e)
{
    var hPadding = (pictureBox1.Width - pictureBox1.BackgroundImage.Width) / 2;
    var vPadding = (pictureBox1.Height - pictureBox1.BackgroundImage.Height) / 2;
    var imgRect = new Rectangle(pictureBox1.Left + hPadding, pictureBox1.Top + vPadding, pictureBox1.BackgroundImage.Width, pictureBox1.BackgroundImage.Height);
    e.Graphics.DrawImage(pictureBox1.BackgroundImage, imgRect);
}