Der*_*zed 64 c# label background
在我的C#表单中,我有一个标签,在下载事件中显示下载百分比:
this.lblprg.Text = overallpercent.ToString("#0") + "%";
Run Code Online (Sandbox Code Playgroud)
Label控件的BackColor属性设置为透明,我希望它显示在PictureBox上.但这似乎不能正常工作,我看到一个灰色的背景,它在图片框的顶部看起来不透明.我怎样才能解决这个问题?
Han*_*ant 153
Label控件很好地支持透明度.只是设计师不会让你正确放置标签.PictureBox控件不是容器控件,因此Form成为标签的父级.所以你看到了表单的背景.
通过向表单构造函数添加一些代码很容易解决.您需要更改标签的Parent属性并重新计算它的位置,因为它现在相对于图片框而不是表单.像这样:
public Form1() {
InitializeComponent();
var pos = this.PointToScreen(label1.Location);
pos = pictureBox1.PointToClient(pos);
label1.Parent = pictureBox1;
label1.Location = pos;
label1.BackColor = Color.Transparent;
}
Run Code Online (Sandbox Code Playgroud)
在运行时看起来像这样:
另一种方法是解决设计时问题.这只是一个属性.添加对System.Design的引用并向项目添加类,粘贴此代码:
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design; // Add reference to System.Design
[Designer(typeof(ParentControlDesigner))]
class PictureContainer : PictureBox {}
Run Code Online (Sandbox Code Playgroud)
crd*_*rdy 39
你可以使用
label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent; // You can also set this in the designer, as stated by ElDoRado1239
Run Code Online (Sandbox Code Playgroud)
您可以使用TextRenderer绘制文本,它将在没有背景的情况下绘制文本:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
TextRenderer.DrawText(e.Graphics,
overallpercent.ToString("#0") + "%",
this.Font,
new Point(10, 10),
Color.Red);
}
Run Code Online (Sandbox Code Playgroud)
当totalpercent值改变时,刷新pictureBox:
pictureBox1.Refresh();
Run Code Online (Sandbox Code Playgroud)
你也可以使用Graphics.DrawString但TextRenderer.DrawText(使用GDI)比DrawString(GDI +)更快