对 PictureBox 的透明控制
- 作者: 尼古拉斯-梅耶斯-氟多-拉格朗-男爵
- 来源: 51数据库
- 2023-02-08
问题描述
在我的 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 控件的 BackColor 属性设置为透明,我希望它显示在 PictureBox 上.但这似乎无法正常工作,我看到灰色背景,在图片框顶部看起来不透明.我该如何解决这个问题?
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 控件不是容器控件,因此 Form 成为标签的父级.所以你会看到表单的背景.
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.
通过向表单构造函数添加一些代码很容易解决.您需要更改标签的 Parent 属性并重新计算它的 Location,因为它现在是相对于图片框而不是表单.像这样:
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 的引用并向您的项目添加一个类,粘贴以下代码:
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 {}
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源