[英]Setting a label background colour to transparent in WinForms make it ignore any images underneath it and displays the form background image instead
I'm working on a very image intensive application.我正在开发一个图像密集型应用程序。
In this example, there is a Panel at the very back with a background image and a PictureBox ontop of that with a background image.在此示例中,在最后面有一个带有背景图像的 Panel 和一个带有背景图像的 PictureBox。 When I add a label ontop of that and set the background colour to be transparent, the background colour displayed is of the Panel background image and it completely ignores the image that's in between the two.
当我在其上添加标签并将背景颜色设置为透明时,显示的背景颜色是面板背景图像,它完全忽略了两者之间的图像。 Am I doing something wrong?
难道我做错了什么?
That's how transparency works in Windows Forms.这就是 Windows 窗体中透明度的工作原理。 It's fake.
这是假的。 A transparent control isn't actually transparent and allowing what's behind it to show through.
透明控件实际上并不透明,它允许显示其背后的内容。 Instead, it just draws a copy of its parent in its own background.
相反,它只是在自己的背景中绘制其父级的副本。 If you want a
PictureBox
to show through a Label
then the Label
has to actually be a child of the PictureBox
.如果您希望
PictureBox
通过Label
显示,则Label
实际上必须是PictureBox
的子级。 The catch is that you cannot do that in the designer, so you have to add the Label
to some other container and then move it to the PictureBox
in code.问题是您无法在设计器中执行此操作,因此您必须将
Label
添加到其他容器,然后将其移动到代码中的PictureBox
。 I suggest that you place the Label
in the exact location you want it in the designer, regardless of its parent container.我建议您将
Label
放置在设计器中您想要的确切位置,无论其父容器如何。 You can then do this in the Load
event handler of your form:然后,您可以在表单的
Load
事件处理程序中执行此操作:
label1.Location = pictureBox1.PointToClient(label1.PointToScreen(Point.Empty));
label1.Parent = pictureBox1;
That code gets the location of the Label
relative to the screen, then translates that to a Point
relative to the PictureBox
and assigns that to the Location
of the Label
.该代码获取
Label
相对于屏幕的位置,然后将其转换为相对于PictureBox
的Point
并将其分配给Label
的Location
。 When the Label
is added to the PictureBox
, it appears at that location, so in the exact same location it was to start with, only inside the PictureBox
.当
Label
添加到PictureBox
时,它会出现在该位置,因此在与它开始时完全相同的位置,仅在PictureBox
内。
Here's an extension method that does the same thing:这是一个做同样事情的扩展方法:
public static class ControlExtensions
{
public static void SetParentWithSameScreenCoordinates(this Control source, Control parent)
{
source.Location = parent.PointToClient(source.PointToScreen(Point.Empty));
source.Parent = parent;
}
}
You can then do this in your Load
event handler:然后,您可以在
Load
事件处理程序中执行此操作:
label1.SetParentWithSameScreenCoordinates(pictureBox1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.