用C#windows应用程序表单覆盖透明的图片框?

时间:2013-11-02 23:06:53

标签: c# winforms

我想放一张背景图片,在背景图片上方我想叠加一个透明的图片框,并尝试将第二个图片框放入:

pictureBox2.BackColor = Color.Transparent;

但它没有用。基本上,我想这样做:

Enter image description here

1 个答案:

答案 0 :(得分:2)

Windows Forms中的透明度未按预期实施。具有透明背景实际上意味着控件使用其父级的背景。这意味着您需要使叠加控制成为原始图片框的子项:

PictureBox overlay = new PictureBox();

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

pictureBox2.Controls.Add(overlay);

如果您希望叠加图片框包含透明图像,则需要实际更改图像:

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);