在图片框透明控制 [英] Transparent control over PictureBox
问题描述
在我的C#窗体我有一个显示在下载事件下载百分比标签:
In my C# Form I have a Label that displays a download percentage in the download event:
this.lblprg.Text = overallpercent.ToString("#0") + "%";
Label控件的背景色属性设置为是透明的,我希望它显示了一个图片。但是,这似乎并没有正常工作,我看到一个灰色的背景,它看起来并不透明的图片框的顶部。我该如何解决这个问题?
The Label control's BackColor property is set to be transparent and I want it to be displayed over a PictureBox. But that doesn't appear to work correctly, I see a gray background, it doesn't look transparent on top of the picture box. How can I fix this?
推荐答案
Label控件支持透明度好。这只是设计者不会让你正确放置的标签。 PictureBox控件不是容器控件,这样形式成为标签的父。所以你看窗体的背景。
The Label control supports transparency well. It is just that the designer won't let you place the label correctly. The PictureBox control is not a container control so the Form becomes the parent of the label. So you see the form's background.
这是很容易添加一些code的窗体构造函数来解决。你需要改变标签的Parent属性,并重新计算它的位置,因为它现在是相对于图片框,而不是形式。像这样的:
It is easy to fix by adding a bit of code to the form constructor. You'll need to change the label's Parent property and recalculate it's Location since it is now relative to the picture box instead of the form. Like this:
public Form1() {
InitializeComponent();
var pos = this.PointToScreen(label1.Location);
pos = pictureBox1.PointToClient(pos);
label1.Parent = pictureBox1;
label1.Location = pos;
label1.BackColor = Color.Transparent;
}
看起来像这样在运行时:
Looks like this at runtime:
另一种方法是要解决的设计时的问题。这只是需要一个属性。添加到System.Design的引用,并添加一个类到您的项目中,粘贴此code:
Another approach is to solve the design-time problem. That just takes an attribute. Add a reference to System.Design and add a class to your project, paste this code:
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design; // Add reference to System.Design
[Designer(typeof(ParentControlDesigner))]
class PictureContainer : PictureBox {}
这篇关于在图片框透明控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!