zoukankan      html  css  js  c++  java
  • [置顶] C#中给Label控件设置BackgroundImage属性

    在C#中,默认情况下是无法给Label设置BackgroundImage属性的,只有Image这个属性,但是在某些特殊的情况下我们又需要设置Label的BackgroundImage属性,因此我们必须对label控件加以改造。Label是继承自Control类的,而Control类是有BackgroundImage这个属性的,Label也有这个属性,只是在VS中我们无法看到而已,微软做了下处理,不希望我们在属性窗口中能够直接设置它。实际上它有很多属性在属性面板中没有显示而已,如下图示:



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









  • 相关阅读:
    PhotoshopCS6中文版图像处理实战从入门到精通
    Web安全开发指南
    OpenStack运维指南
    Word/Excel/PPT 2016高效办公实战从入门到精通
    UG NX 8.5中文版基础教程
    Moldflow 2018模流分析从入门到精通:升级版
    数据库与数据处理:Access 2010实现
    iOS开发网络数据之AFNetworking使用1
    AFNetworking2.5使用2
    iOS项目的完整重命名方法图文教程
  • 原文地址:https://www.cnblogs.com/kevinGao/p/2776056.html
Copyright © 2011-2022 走看看