Set the BackgroundImage property to the Label control in C #

In C #, default is not to set the BackgroundImage property of Label, Image only the property, but in some special cases we need to set the Label's BackgroundImage property, so we have to be modified to label controls. Label is inherited from the Control class, and the Control class is BackgroundImage this property, Label also has this property, but in VS we can not see it, Microsoft made under the deal, you do not want us to be able to set it directly in the Properties window . In fact it has many properties not only displayed in the Properties panel, illustrated as follows:



Therefore, we can rewrite the Label control code can be a little code as shown below, we write control inherits Label, rewrite its two methods can be.

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);









转载于:https://www.cnblogs.com/kevinGao/archive/2011/12/02/2279597.html

Guess you like

Origin blog.csdn.net/weixin_34129696/article/details/93350804