C#中给LABEL控件设置BACKGROUNDIMAGE属性

本文介绍了一种通过继承Label控件并重写其绘图方法来实现带有背景图片的自定义Label的方法。通过简单的代码修改,可以为Label控件添加背景图片,并调整其绘制方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们可以对Label控件代码稍加改写即可,代码如下图所示,我们写个控件继承Label,重写它的2个方法即可。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace Tempus.Component
{
    public partial class LabelEx2 : Label
    {
        

        public LabelEx2()
        {
           
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            return;
        }

        protected override void OnPaint(PaintEventArgs e)
        {

            //判断BackGroundImage是否为空
            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);
        }
       
    }
}

调用时设置这个Label控件的BackgroundImage属性即可,Demo代码如下:

string strWineDetail1 = Application.StartupPath + "\\Resources\\" + "WineDetail1.jpg";
lblWineInfo.BackgroundImage = Image.FromFile(strWineDetail1);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值