Monday, July 22, 2013

How to overlay transparent images using C#

A few days ago someone asked me to code a little program using C#, the program was simple: three comboboxes, the first one will show a shape of X sides (an image in a picturebox), the second one will show something behind that image, and the third one show a color. Pretty easy. If you’re a programmer you already did half or all the coding in your head.

Easy as hell, 40 minutes tops coding and testing the boxes and trying out all possible outputs, all good… until I get into the images. I spend over 2 hours trying to overlap the images on the pictureboxes without any success (at the end I succeeded, obviously) because the way Visual handle transparent images is not how we think it works.

First of all, for those of you who don’t know, when you put a transparent image into the interface, the system will render the background of the parent of the picturebox, creating the illusion of transparency. This doesn’t work too well when overlaying pictureboxes because these don’t have parents, the main Form is the parent. So, when you put one over another, you get something like this:

iamge1

  • The image in the middle is transparent in the center and shows the color of the form behind it as intended.
  • The image on the left are dotted lines, these are also transparent and show the color of the form behind them, but they don’t appear behind the center image.
  • The color to the right, doesn’t appear behind the center image because is not the parent. And as you can’t guess, it won’t appear behind of the left one neither.

Many people suggested to force the parent into the images. Something like:

FrontImage.parent = Backimage;

A fuckin’ mess.

image2

After a while of doing searches (a lot of searches), I was about to give up, until I decided to do the only thing I hadn’t tried yet.

FrontImage.BackgroundImage = BackImage;

And that’s it. As simple as that. Assuming that the images are already in your resources, it will be something like:

pictureBox1.Image = Properties.Resources.FrontImage
pictureBox1.BackgroundImage = Properties.Resources.BackImage;

Of course, for this example we need the color, so:

pictureBox1.Image = Properties.Resources.FrontImage
pictureBox1.BackgroundImage = Properties.Resources.BackImage;
pictureBox1.BackColor = System.Drawing.Color.ColorYouWant;

And the result is pretty much what I wanted:

image3

Of course, this may seem and sound dumb, “Who would need to overlay a shape over a line over a color?”… many people, actually. And most of them are forced to create a custom class just for this. Which seems like a lot of work I don’t want to do.

1 comment:

  1. Would you be so kind as to post a small complete example of code.
    thanks.
    Dino

    ReplyDelete