我有一个自定义控件,它有两个PictureBox控件,分别是动画和label控件。
子索引被设置,这样标签总是在顶部,但是图片框是互换的,所以当动画时,它们每次都显示不同的图像。
据我所知,标签需要有一个父控件,它可以支持半透明的颜色(Argb)。由于标签有活动图片框作为其父,它也将被动画,这不是我想要的。
是否有办法解决孩子相对于父母的位置?
发布于 2015-12-17 16:01:36
若要具有透明的label控件,可以重写OnPaint方法并绘制与label相交的所有控件,最后绘制标签的背景和文本。
另外,在移动图片框时,不要忘记调用透明标签的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;
}
}
}https://stackoverflow.com/questions/34335157
复制相似问题