如何使透明Image下方的TableLayoutPanel可见(C# WinForms)
解决方案
方法一:调整控件父子关系(最简单,适合新手)
Windows Forms中控件的“透明”是相对于父控件背景的,而非穿透显示下方同级控件。默认情况下,PictureBox和TableLayoutPanel同属Form子控件时,透明区域只会显示Form背景。要让透明区域透出TableLayoutPanel,只需修改PictureBox的父控件为TableLayoutPanel:
- 在Visual Studio设计器中,先选中
TableLayoutPanel,再拖入PictureBox(确保PictureBox成为TableLayoutPanel的子控件)。 - 设置
PictureBox的Location为(0,0),Size与TableLayoutPanel完全一致,让它覆盖整个TableLayoutPanel。 - 将带透明孔位的PNG图片设置为
PictureBox的Image属性(必须是支持Alpha透明的格式,比如PNG)。 - 关键:把
PictureBox的BackColor设为Color.Transparent。
完成后,PictureBox的透明区域就会显示下方TableLayoutPanel的单元格内容——此时它的父控件是TableLayoutPanel,透明效果会继承父控件的显示内容。
如果设计器中没将PictureBox拖入TableLayoutPanel,可手动在属性面板修改Parent为tableLayoutPanel1,再调整位置和大小。
方法二:自定义透明PictureBox(无需调整层级)
如果不想修改控件父子关系,可以自定义一个PictureBox,让它主动绘制下方控件的内容:
using System.Drawing; using System.Windows.Forms; public class TransparentOverlayPictureBox : PictureBox { protected override void OnPaintBackground(PaintEventArgs e) { // 跳过默认背景绘制,转而绘制下方控件的内容 if (Parent != null) { using (Bitmap buffer = new Bitmap(Width, Height)) { // 获取当前控件在父容器中的区域,绘制到缓冲位图 Rectangle parentRect = new Rectangle(PointToScreen(Point.Empty), Size); parentRect = Parent.RectangleToClient(parentRect); Parent.DrawToBitmap(buffer, parentRect); e.Graphics.DrawImage(buffer, Point.Empty); } } } }
使用步骤:
- 编译项目后,自定义控件会出现在工具箱中,拖入Form并覆盖TableLayoutPanel。
- 设置控件的
Image为你的透明图片即可。
内容的提问来源于stack exchange,提问作者abaww
相关产品推荐
相关产品推荐

