Give transparent backgrounds to images displayed on buttons in C#

[transparent backgrounds]

This example shows how to give transparent backgrounds to the images displayed on a button.

If you give buttons images that have transparent backgrounds, then the button’s background can show through. If the images don’t have transparent backgrounds, the result are rectangular blocks sitting on top of the buttons. There are a couple of ways you can work around this.

First, you can give the images transparent backgrounds as described in the post Make a tool that creates PNG files with transparent backgrounds in C#.

[transparent backgrounds]Second, you can color the images’ backgrounds so they match the button’s backgrounds. Note that the appearance of buttons may differ in different versions of Windows so this may not work very well. For example, in the picture on the right the buttons don’t have solid colored backgrounds.

This example uses the following MakeButtonTransparent method to give a buttons’ images a transparent background at run time.

// Give the button a transparent background.
private void MakeButtonTransparent(Button btn)
{
    Bitmap bm = (Bitmap)btn.Image;
    bm.MakeTransparent(bm.GetPixel(0, 0));
}

This method gets the button’s current image as a Bitmap. It calls the Bitmap object’s MakeTransparent method to convert all of the pixels of a particular color into a transparent color. The color that the code converts is whatever color is in the image’s upper left corner. The image is already displayed in the button so the change appears automatically.

So the procedure is to make the button’s image so all of the background pixels have the same color as the pixel in the upper left corner. Then when the form loads, call MakeButtonTransparent for the button.

Note that some controls such as ToolStripButton, ToolStripSplitButton, and ToolStripMenuItem have an ImageTransoarentColor property that does this for you. Simply set this property to the color of the background pixels in the image and you’re all set.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, graphics, image processing and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *