[英]Setting a label background colour to transparent in WinForms make it ignore any images underneath it and displays the form background image instead
我正在开发一个图像密集型应用程序。
在此示例中,在最后面有一个带有背景图像的 Panel 和一个带有背景图像的 PictureBox。 当我在其上添加标签并将背景颜色设置为透明时,显示的背景颜色是面板背景图像,它完全忽略了两者之间的图像。 难道我做错了什么?
这就是 Windows 窗体中透明度的工作原理。 这是假的。 透明控件实际上并不透明,它允许显示其背后的内容。 相反,它只是在自己的背景中绘制其父级的副本。 如果您希望PictureBox
通过Label
显示,则Label
实际上必须是PictureBox
的子级。 问题是您无法在设计器中执行此操作,因此您必须将Label
添加到其他容器,然后将其移动到代码中的PictureBox
。 我建议您将Label
放置在设计器中您想要的确切位置,无论其父容器如何。 然后,您可以在表单的Load
事件处理程序中执行此操作:
label1.Location = pictureBox1.PointToClient(label1.PointToScreen(Point.Empty));
label1.Parent = pictureBox1;
该代码获取Label
相对于屏幕的位置,然后将其转换为相对于PictureBox
的Point
并将其分配给Label
的Location
。 当Label
添加到PictureBox
时,它会出现在该位置,因此在与它开始时完全相同的位置,仅在PictureBox
内。
这是一个做同样事情的扩展方法:
public static class ControlExtensions
{
public static void SetParentWithSameScreenCoordinates(this Control source, Control parent)
{
source.Location = parent.PointToClient(source.PointToScreen(Point.Empty));
source.Parent = parent;
}
}
然后,您可以在Load
事件处理程序中执行此操作:
label1.SetParentWithSameScreenCoordinates(pictureBox1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.