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

来源:互联网 发布:国际顶级域名干嘛的 编辑:程序博客网 时间:2024/05/29 01:55

我们可以对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);



0 0
原创粉丝点击