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:
- 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.
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:
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.
Would you be so kind as to post a small complete example of code.
ReplyDeletethanks.
Dino
The writer of this blog is really very professional. Every single line of this article is well written. New use of vocabulary is a great effort. At the same time tense, indirect speech was also sued in good manner.ทำจมูกที่ไหนดี
ReplyDelete