1

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.

Amelse Etomer
  • 1,253
  • 10
  • 28
  • 1
    You could use code like [this](http://stackoverflow.com/a/6501997/2330053) by @AlexAza to create a properly resized image that can be used with the `None` layout. – Idle_Mind Jun 12 '13 at 16:06
  • Thanks, that is what I was roughly doing anyways. The resizing itself hasn't be a problem. – Amelse Etomer Jun 14 '13 at 10:39

1 Answers1

2

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);
    }
}
King King
  • 61,710
  • 16
  • 105
  • 130