SavageStyle
SavageStyle

Reputation: 61

C# Make a form's background transparent (to display .png background with half-transparent pixels)

PNG image have transparent parts and I want this image as background for my form.
I've set ControlStyles.SupportsTransparentBackColor to true and used this.BackColor = Color.Transparent; but this is just not working at all, the back color appears solid gray when im starting app. Even if I set BackColor to Transparent in Properties->Appearence. I can see it Transparent in form design preview but it still appears solid gray when Im start the application.
Playing with TransparencyKey also gaves me a bad results - the half-transparent pixels of PNG image became colored with TransparencyKey color and i can't use Transparent color for TransparencyKey. Looking for some help.
EXAMPLE: https://i.sstatic.net/u9p6N.jpg

Upvotes: 1

Views: 2272

Answers (1)

PiotrWolkowski
PiotrWolkowski

Reputation: 8792

You may use the TransparencyKey incorrectly. The idea behind this property is that the color specified as the TransparencyKey will be transparent. E.g. if you set myForm.TransparencyKey = Color.Red anything that is red will be transparent. However, if the shade of red is different than the one described as Color.Red it won't be transparent.

Or, to put it another way, it will result in a transparent background:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.BackColor = Color.FromArgb(100, 0, 0);
        this.TransparencyKey = Color.FromArgb(100, 0, 0);
    }
}

But this will not be transparent:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.BackColor = Color.FromArgb(99, 0, 0);
        this.TransparencyKey = Color.FromArgb(100, 0, 0);
    }
}

So now if your image has white background and you set this.TransparencyKey = Color.White only white parts of the image will be transparent. But if there are any grayish, white-ish areas you will see this color instead of transparent background.

If that's the case you may need to edit the image to be sure the background is everywhere of the same color.

Upvotes: 1

Related Questions