我有一个自定义的控制有两个的PictureBox控件被动画和标签控制他们。
该子指标被设定成标签总是在顶部,但图片框的互换这么活跃,当他们每次显示不同的图像。
据我了解,标签需要有一个父控件,在它上面可以支持半透明颜色(Argb)。由于标签具有活动图片框作为其父标签,因此它也将被动画化,而这根本不是我想要的。
有没有办法确定孩子相对于父母父母的地位?
要拥有透明的标签控件,您可以覆盖该OnPaint方法并绘制与标签相交的所有控件,最后绘制标签的背景和文本。
同样,在移动图片框时,请不要忘记调用Invalidate()透明标签的方法。
屏幕截图
样例实施
public class TransparentLabel : Label
{
public TransparentLabel()
{
this.transparentBackColor = Color.Blue;
this.opacity = 50;
this.BackColor = Color.Transparent;
}
protected override void OnPaint(PaintEventArgs e)
{
if (Parent != null)
{
using (var bmp = new Bitmap(Parent.Width, Parent.Height))
{
Parent.Controls.Cast<Control>()
.Where(c => Parent.Controls.GetChildIndex(c) > Parent.Controls.GetChildIndex(this))
.Where(c => c.Bounds.IntersectsWith(this.Bounds))
.OrderByDescending(c => Parent.Controls.GetChildIndex(c))
.ToList()
.ForEach(c => c.DrawToBitmap(bmp, c.Bounds));
e.Graphics.DrawImage(bmp, -Left, -Top);
using (var b = new SolidBrush(Color.FromArgb(this.Opacity, this.TransparentBackColor)))
{
e.Graphics.FillRectangle(b, this.ClientRectangle);
}
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, Color.Transparent);
}
}
}
private int opacity;
public int Opacity
{
get { return opacity; }
set
{
if (value >= 0 && value <= 255)
opacity = value;
this.Invalidate();
}
}
public Color transparentBackColor;
public Color TransparentBackColor
{
get { return transparentBackColor; }
set
{
transparentBackColor = value;
this.Invalidate();
}
}
[Browsable(false)]
public override Color BackColor
{
get
{
return Color.Transparent;
}
set
{
base.BackColor = Color.Transparent;
}
}
}
Run Code Online (Sandbox Code Playgroud)