对 PictureBox 的透明控制

时间:2023-02-03
本文介绍了对 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 控件的 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 {}

这篇关于对 PictureBox 的透明控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:处理动态时抛出很多第一次机会 Microsoft.CSharp.RuntimeBinderExceptions 下一篇:捕获表单之外的鼠标/键盘事件(应用程序在后台运行)

相关文章

最新文章