Override a transparent picturebox in C# windows ap

2020-07-27 05:46发布

I want to put in a background image, and above the background image I want to superimpose a transparent picturebox and tried to put the second picturebox like so:

pictureBox2.BackColor = Color.Transparent;

But it did not work. Basically, I would like to do this:

Enter image description here

标签: c# winforms
1条回答
等我变得足够好
2楼-- · 2020-07-27 06:17

Transparency in Windows Forms isn't implemented as one would expect. Having a transparent background actually means that a control uses the background of its parent. This means that you need to make your overlay control a child of the original picture box:

PictureBox overlay = new PictureBox();

overlay.Dock = DockStyle.Fill;
overlay.BackColor = Color.FromArgb(128, Color.Blue);

pictureBox2.Controls.Add(overlay);

If you want the overlay picture box to contain a transparent image you need to actually change the image:

PictureBox overlay = new PictureBox();
overlay.Dock = DockStyle.Fill;
overlay.BackColor = Color.Transparent;

Bitmap transparentImage = new Bitmap(overlayImage.Width, overlayImage.Height);
using (Graphics graphics = Graphics.FromImage(transparentImage))
{
    ColorMatrix matrix = new ColorMatrix();
    matrix.Matrix33 = 0.5f;

    ImageAttributes attributes = new ImageAttributes();
    attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

    graphics.DrawImage(overlayImage, new Rectangle(0, 0, transparentImage.Width, transparentImage.Height), 0, 0, overlayImage.Width, overlayImage.Height, GraphicsUnit.Pixel, attributes);
}

overlay.Image = transparentImage;

pictureBox2.Controls.Add(overlay);
查看更多
登录 后发表回答