Title: Make transparent button images in C#
It seems like I keep writing this program because I need to make button images fairly often. I wanted to use a simple image with a transparent background for a button image. Unfortunately MSPaint doesn't know how to save images with transparent backgrounds. Fortunately C# does.
This example draws the image shown and saves it into a file with a transparent background. To make other images, you need to modify the following Form_Load event handler to draw something else.
// The bitmap.
Bitmap TheBitmap = new Bitmap(16, 16);
// Draw the image to save.
private void Form1_Load(object sender, EventArgs e)
// Fit the picture we draw.
picCanvas.SizeMode = PictureBoxSizeMode.AutoSize;
// Make the bitmap.
TheBitmap = new Bitmap(16, 16);
using (Graphics gr = Graphics.FromImage(TheBitmap))
gr.SmoothingMode = SmoothingMode.AntiAlias;
// Give it a transparent background.
using (Pen the_pen = new Pen(Color.Blue, 3))
the_pen.EndCap = LineCap.Round;
the_pen.StartCap = LineCap.Round;
the_pen.LineJoin = LineJoin.Round;
// Down expander.
Point points =
new Point(3, 2),
new Point(8, 7),
new Point(13, 2),
for (int i = 0; i < points.Length; i++)
points[i].Y += 6;
//// Up expander.
//Point points =
// new Point(3, 13),
// new Point(8, 8),
// new Point(13, 13),
//for (int i = 0; i < points.Length; i++)
// points[i].Y -= 6;
// Display the result.
picCanvas.Image = TheBitmap;
The Load event handler sets the PictureBox control's SizeMode property to AutoSize so it sizes itself to fit the picture. It then creates a 16×16 bitmap and a Graphics object to use for drawing on it. It sets the Graphics object's SmoothingMode property to AntiAlias so the program will produce a smooth result.
Next the code clears the bitmap with the color Transparent. That gives the image the transparent background.
The code then does the actual drawing. In this case, the code makes a blue pen that's three pixels wide. It sets the pen's StartCap, EndCap, and LineJoin properties to Round so any lines it draws have rounded ends and corners. The program then uses that pen to draw two downward-pointing chevron shapes. (Commented code draws two upward-pointing shapes.)
The code finishes by displaying the resulting picture.
If you open the File menu and select Save As, the program displays a file save dialog. If you pick a file and click Save, the program saves the image by calling the SaveImage extension method described in the post Save images with an appropriate format depending on the file name's extension in C#. See the code and that post for more details.
Now you can set a button's Image property to the saved picture to give the button a nice appearance. See the post Give transparent backgrounds to images displayed on buttons in C# for more information on that topic.
Download the example to experiment with it and to see additional details.