Travis Travis - 3 months ago 18
C# Question

Making a background image scale with button size

I'm trying to add some background images to a few buttons in my Win Forms application. The three images are different sizes (ie pixel dimensions don't match, one is 128x128 and another is 256x256). I need the buttons to be identical in size (otherwise the GUI is horribly asymmetrical). Without changing the actual image files, how can I get the images to scale with button size?

I've tried creating my own class, and adding an event handler for the button resize event, but that doesn't seem to work. My code:

class CustomButton : Button {

internal void CustomButton_Resize( object sender, EventArgs e ) {
if ( this.BackgroundImage == null ) {
return;
}

var pic = new Bitmap( this.BackgroundImage, this.Width, this.Height );
this.BackgroundImage = pic;
}
}


and in the form:

this.buttonOne.Resize += new System.EventHandler(this.buttonOne.CustomButton_Resize);


Forgot to mention, the above code does not resize the images at all. The buttons still need to have different sizes to display the images completely.

Answer

The easy programmatic way

Say I have a button btn1, Following code is working perfectly in visual-studio-2010.

private void btn1_Click(object sender, EventArgs e)
{
    btn1.Width = 120;
    btn1.Height = 100;
}
void btn1_Resize(object sender, EventArgs e)
{
    if ( this.BackgroundImage == null )
          return;
    var bm = new Bitmap(btn1.BackgroundImage, new Size(btn1.Width, btn1.Height));
    btn1.BackgroundImage = bm;
}

The better way

You can add eventHandler in the constructor of your custombutton (just to ensure that you are adding eventhandler correctly)

class CustomButton : Button
{    
    CustomButton()
    {
        this.Resize += new System.EventHandler(buttonOne.CustomButton_Resize);
    }
    void CustomButton_Resize( object sender, EventArgs e )
    {
       if ( this.BackgroundImage == null )
          return;
       var pic = new Bitmap( this.BackgroundImage, new Size(this.Width, this.Height) );
       this.BackgroundImage = pic;          
    }
}

Now when you will resize the button anywhere your image will get fit(scaled) to its new size.