問題描述
在我的 C# 表單中,我有一個(gè)在下載事件中顯示下載百分比的標(biāo)簽:
In my C# Form I have a Label that displays a download percentage in the download event:
this.lblprg.Text = overallpercent.ToString("#0") + "%";
Label 控件的 BackColor 屬性設(shè)置為透明,我希望它顯示在 PictureBox 上.但這似乎無法正常工作,我看到灰色背景,在圖片框頂部看起來不透明.我該如何解決這個(gè)問題?
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控件很好的支持透明.只是設(shè)計(jì)師不會(huì)讓你正確放置標(biāo)簽.PictureBox 控件不是容器控件,因此 Form 成為標(biāo)簽的父級.所以你會(huì)看到表單的背景.
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.
通過向表單構(gòu)造函數(shù)添加一些代碼很容易解決.您需要更改標(biāo)簽的 Parent 屬性并重新計(jì)算它的 Location,因?yàn)樗F(xiàn)在是相對于圖片框而不是表單.像這樣:
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;
}
在運(yùn)行時(shí)看起來像這樣:
Looks like this at runtime:
另一種方法是解決設(shè)計(jì)時(shí)問題.那只需要一個(gè)屬性.添加對 System.Design 的引用并向您的項(xiàng)目添加一個(gè)類,粘貼以下代碼:
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 {}
這篇關(guān)于對 PictureBox 的透明控制的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!