简体   繁体   English

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

[英]How do I paint a pictureboxes 'centered' background image to panel?

I was nicely supplied a code from Alex M, for painting the background image to a panel but realized that if a PictureBox 's BackgroundImage has its Center image property set, the drawn image becomes stretched but not centered. 我从Alex M那里很好地提供了一个代码,用于将背景图像绘制到面板上,但是我意识到,如果PictureBoxBackgroundImage设置了其Center image属性,则绘制的图像会拉伸但不会居中。 I so far have this code: 到目前为止,我有以下代码:

private void panel1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawImage(pictureBox1.BackgroundImage, 
        new Rectangle(pictureBox1.Location, pictureBox1.Size));
}

This draws the background image to the panel but if pictureBox1 's background image property is set to CENTER, it does not paint the image in the Center of the Rectangle, but instead stretches the image to fit the rectangle. 这会将背景图像绘制到面板上,但是如果pictureBox1的背景图像属性设置为CENTER,则不会在矩形的中心绘制图像,而是拉伸图像以适合矩形。

The only possible solution I've found is here but I can't make any sense of it. 我找到的唯一可能的解决方案是在这里,但我对此毫无意义。

The reason the image is being stretched is because the second parameter to DrawImage specifies the location and size of where you're drawing the image, and you're specifying the entire area of the picture box, not the area of the image itself. 拉伸图像的原因是因为DrawImage的第二个参数指定了绘制图像的位置和大小,并且指定了图片框的整个区域,而不是图像本身的区域。

If you want to center it, try something like this: 如果要居中,请尝试以下操作:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM