Skip to main content
 首页 » 编程设计

C# Windows 窗体标签 BackgroundImage

2024年02月06日11softidea

我想在 Label 上设置背景图片。 我发现 Microsoft不允许这样做。但是,我想自己实现。 代码在下面,问题是如何以编程方式设置背景图像? 仍然没有要设置的 BackgroundImage 属性。

class BackgroundImageLabel : Label 
{ 
    public BackgroundImageLabel() 
    { 
 
    } 
 
    protected override void OnPaintBackground(PaintEventArgs e) 
    { 
        return; 
    } 
 
    protected override void OnPaint(PaintEventArgs e) 
    { 
        //is BackGroundImage null 
        if (this.BackgroundImage != null) 
        { 
 
                e.Graphics.DrawImage(this.BackgroundImage, new System.Drawing.Rectangle(0, 0, this.Width, this.Height), 
                this.Location.X, this.Location.Y, this.Width, this.Height, 
                   System.Drawing.GraphicsUnit.Pixel);       
        } 
 
        e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 
        SolidBrush drawBrush = new SolidBrush(this.ForeColor); 
        e.Graphics.DrawString(this.Text, this.Font, drawBrush, new System.Drawing.Rectangle(0, 0, this.Width, this.Height)); 
        //base.OnPaint(e); 
    } 
} 

编辑

我遇到的另一个问题是,无论我如何更改设置,标签都是黑色的。 我不知道是什么原因。谁能帮帮我?

请您参考如下方法:

BackgroundImage 属性由Label 的基类Control 类实现。所以每个控件都可以拥有背景图像。但正如您从 Label 在设计器中的行为方式可以看出的那样,他们对其进行了修补以使其不可用。

你会想知道他们用它做了什么。您可以使用反编译器来完成此操作,但今天最好使用 Reference Source .一个非常漂亮的网站,可让您轻松浏览 .NET Framework 中的源代码。在搜索框中输入“Label.BackgroundImage”。

您会发现它并没有发生特别剧烈的变化,它只是获取了几个属性以隐藏该属性。因此,您要做的第一件事是自己重写 BackgroundImage 并再次取消这些属性:

using System; 
using System.ComponentModel; 
using System.Drawing; 
using System.Windows.Forms; 
 
class BackgroundImageLabel : Label { 
    [Browsable(true), EditorBrowsable(EditorBrowsableState.Always), 
     DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] 
    public override Image BackgroundImage { 
        get { 
            return base.BackgroundImage; 
        } 
        set { 
            base.BackgroundImage = value; 
        } 
    } 
} 

宾果游戏,效果很好。

您必须将 AutoSize 属性设置为 False,这可能是他们决定隐藏该属性的原因。您也可以覆盖它,如果您愿意,您现在知道该怎么做了:)