[英]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.