简体   繁体   English

在 WinForms 中将标签背景颜色设置为透明使其忽略其下方的任何图像并显示表单背景图像

[英]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相对于屏幕的位置,然后将其转换为相对于PictureBoxPoint并将其分配给LabelLocation 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM