如何用c#制作两个透明层?
有三个连续的图层,
picturebox1(.jpg) -> label1 -> picturebox2(.png transparent)
我想要的是使label1和pictrurebox2对picturebox1透明,这样label1可以通过picturebox2看到但它无法正常工作..
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() .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); } }
透明PictureBox
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() .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); } }