有连续的三层,
picturebox1(.jpg) -> label1 -> picturebox2(.png transparent)
我想要的是让label1和picturebox2对picturebox1透明这样可以通过 picturebox2 看到 label1 但它不起作用..
public Form1()
{
InitializeComponent();
label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent;
pictureBox2.Parent = pictureBox1;
pictureBox2.BackColor = Color.Transparent;
picturebox2.BringToFront();
}
所以请帮帮我
如果你需要一个支持透明度的控件,你应该覆盖控件的绘制并按以下顺序绘制控件:
- 在位图上绘制受您控制(基于 z-index)的同一容器中的所有控件。
- 然后在您的控件的图形上绘制该位图。
- 最后绘制控件的内容。
- 此外,您的控件的
BackColor
应该是Color.Transparent
。
这是创建 TransparentLabel
和 TransparentPictureBox
控件的结果。在下图中,依次是标签、图像、标签、图像和标签,您可以看到图片框和标签已呈现为具有透明背景并符合 z-index:
透明标签
class TransparentLabel : Label
{
public TransparentLabel()
{
this.BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs e)
{
if (Parent != null && this.BackColor == Color.Transparent)
{
using (var bmp = new Bitmap(Parent.Width, Parent.Height))
{
Parent.Controls.Cast<Control>()
.Where(c => Parent.Controls.GetChildIndex(c) > Parent.Controls.GetChildIndex(this))
.Where(c => c.Bounds.IntersectsWith(this.Bounds))
.OrderByDescending(c => Parent.Controls.GetChildIndex(c))
.ToList()
.ForEach(c => c.DrawToBitmap(bmp, c.Bounds));
e.Graphics.DrawImage(bmp, -Left, -Top);
}
}
base.OnPaint(e);
}
}
透明图片框
class TransparentPictureBox : PictureBox
{
public TransparentPictureBox()
{
this.BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs e)
{
if (Parent != null && this.BackColor==Color.Transparent)
{
using (var bmp = new Bitmap(Parent.Width, Parent.Height))
{
Parent.Controls.Cast<Control>()
.Where(c => Parent.Controls.GetChildIndex(c) > Parent.Controls.GetChildIndex(this))
.Where(c => c.Bounds.IntersectsWith(this.Bounds))
.OrderByDescending(c => Parent.Controls.GetChildIndex(c))
.ToList()
.ForEach(c => c.DrawToBitmap(bmp, c.Bounds));
e.Graphics.DrawImage(bmp, -Left, -Top);
}
}
base.OnPaint(e);
}
}
我是一名优秀的程序员,十分优秀!