透明度确实有效nested控制;但它是不支持重叠控件在winform下。时期。
您可以尝试使用解决方法two标签,一个嵌套在面板under铅、pb中的其他.
这是一个例子:
Label l1 = new Label() { Text = "Hello World", BackColor = Color.Transparent };
Label l2 = new Label() { Text = "Hello World", BackColor = Color.Transparent };
l1.Parent = scrollPanel;
l2.Parent = picBox;
Point pt = new Point(picBox.Right - 30, 30);
l1.Location = pt;
pt.Offset(-picBox.Left, -picBox.Top);
l2.Location = pt;
上面的代码也可以放入可重用的函数中:
Label overlayLabel(Label source, Control target)
{
Label old = source.Tag as Label;
if (old != null && old.Parent == target) target.Controls.Remove(old);
Label lbl = new Label();
// copy all necessary properties here:
lbl.Text = source.Text;
lbl.Font = source.Font;
lbl.AutoSize = source.AutoSize;
lbl.Size = source.Size;
lbl.Anchor = source.Anchor; // may work or not!
lbl.BackColor= source.BackColor;
lbl.ForeColor = source.ForeColor;
// etc..
Point pt = source.Location;
pt.Offset(-target.Left , -target.Top);
lbl.Location = pt;
lbl.Parent = target;
source.Tag = lbl;
return lbl;
}
在你的代码中你可能会这样称呼它;您可以存储返回的引用:
panel2.Controls.Add(ctrLabel);
Label ctrLabelOverlay = overlayLabel(ctrLabel, ctrl );
..或者丢弃它,因为它负责清理之前的覆盖层,该覆盖层存储在Tag
of the Label
..:
panel2.Controls.Add(ctrLabel);
overlayLabel(ctrLabel, ctrl );
But最直接的方法就是draw那些东西,即文本和图像yourself。面板中的两行左右Paint
事件..:
if (img != null)
{
Rectangle rect = new Rectangle(pt1, img.Size);
e.Graphics.DrawImage(img, rect);
e.Graphics.DrawString("Hello World", Font, Brushes.Black, pt2);
}
您所需要的只是计算两个位置pt1
and pt2
。如果您的 Picturbox 正在拉伸或缩放,您还需要将源矩形写入DrawImage
可以缩放/拉伸图像的重载。
强制执行显示调用panel2.Invalidate
每当有事情发生变化..
更简单,更强大,除非你需要特殊的能力Label
or PictureBox
..
请注意,所有事情都发生在代码中,因此不要指望事情会显示在设计器中。编写代码以使其确实显示在 VS 设计器中并不那么容易。