在MSDN中:
Transparent controls in WinForms are transparent relative to their parent, not to other controls. Transparency in WinForms is more akin to camouflage than true transparency. A transparent control doesn’t actually let you see the control behind it through the form. It asks its parent to draw its own background on the "transparent" control. This is why a transparent control shows the form behind it, but covers up any other controls.
方法一:所以图片绘制在一起。
在Winform中如果将一个透明图片放在窗体上能正常显示透明,但是如果将该图片放在另一个控件上会导致不能显示透明效果。
解决这种情况,可以采取在控件上使用GDI+绘画出透明图片。
这里我们就以一个pictureBox2控件上面重叠一张png透明图片为例:
我们只需要给pictureBox2控件添加Paint事件,然后对png透明图片进行绘制即可,代码如下:
1
2
3
4
5
6
|
private
void
pictureBox2_Paint(
object
sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Image image = Image.FromFile(
@"e:\cclock.png"
);
g.DrawImage(image,
new
Point(20, 10));
}
|
方法二:底层图片绘制在一起。
将控件作为父控件的一部分进行绘图,并作为背景。此时再加入透明图片,即可看到透明效果。即如果要后面显示控件。那还得把控件画进去 背景显示。
Point point =
new
Point(0, 0);
PictureBox p = pictureBox1;
point = pictureBox1.Location;
Bitmap b =
new
Bitmap(panel1.Width, panel1.Height);
panel1.Controls.Remove(p);
panel1.DrawToBitmap(b,
new
Rectangle(0, 0, b.Width, b.Height));
pictureBox1.BackColor = Color.FromArgb(80, 0, 0, 0);
panel1.BackgroundImage = b;
panel1.Controls.Add(p);
p.Location = point;
p.BringToFront();
panel1.BackColor = Color.FromArgb(80, 255, 0, 0);
pictureBox1.Visible =
false
;
Bitmap b =
new
Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(b,
new
Rectangle(0, 0, b.Width, b.Height));
pictureBox1.Visible =
true
;
//pictureBox1.BackColor = Color.FromArgb(80, 0, 0, 0);
panel1.BackgroundImage = b;