Reputation: 1253
I am using Windows Forms and I'd like to place a background image in the upper left corner of my panel. I'd like to have the original height:width-ratio
of the image preserved and the image should fill the control as much as possible.
ImageLayout.Zoom
centers the image, which I don't like, but preserves the ratio which is good.
ImageLayout.Stretch
puts the image in the upper left corner (in all other corners) as desired, but does not preserve the ratio.
So far I've used the approach of placing a picturebox into my panel that is resized based on its parent's size, when the parent is resized. I can achieve the desired effect, but I feel that there must be a nicer and built-in way.
Upvotes: 1
Views: 2393
Reputation: 63327
try this:
public class CustomPanel : Panel
{
int x, y;
public CustomPanel()
{
DoubleBuffered = true;
}
float scale;
protected override void OnBackgroundImageChanged(EventArgs e)
{
scale = (float)BackgroundImage.Width / BackgroundImage.Height;
base.OnBackgroundImageChanged(e);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
if(BackgroundImage == null) base.OnPaintBackground(e);
else {
e.Graphics.FillRectangle(new SolidBrush(BackColor), ClientRectangle);
e.Graphics.DrawImage(BackgroundImage, new Rectangle(0, 0, x,y));
}
}
protected override void OnSizeChanged(EventArgs e)
{
if (scale > (float)Width / Height)
{
x = Width;
y = (int)(Width / scale);
}
else
{
y = Height;
x = (int)(Height * scale);
}
base.OnSizeChanged(e);
}
}
Upvotes: 2