设置Tlabel的背景为透明

原文来自:http://www.cnblogs.com/WuCountry/archive/2007/06/27/797907.html

问题很简单不是吗,把Label的BackColor设置成Color.Transparent,然后它就成透明了!表面上看是这样的,但实际上是让它的背景与它的Parent控件的背景一样,这样看上去就是透明的了,实际在它的OnPaintBackGround中,还是完成了一样的绘图工作。

而它这个Label在一个图片上时,你会发现它又变得不透明了,它的背景颜色与PictureBox的背景颜色是一样的。

而我只想要一个可以在图片上也透明的Label。用Google找了一下,没什么结果,大多数是把BackColor修改一下的,当然,也有一些高级方法的:

this.SetStyle(ControlStyles.SupportsTransparentBackColor,true);

其结果与设置背景颜色是一样的,在图片上还是不能透明。

于是我想自己重新写一个透明的label,决定从原来的Label派生,在背景透明时,不去画背景,而只画文字。直接重载OnPaint和OnPaintBackground两个函数,结果发现背景变成黑色的了。郁闷!当OnPaintBackground函数什么也不做时,它实际上用默认的黑色给画了背景。其实我想要的就是让主窗口忽略Label的背景,用原来区域上的图形来绘制该控件的背景。但问题是:我没有办法得到主窗口的给定区域的背景。想用Graphics.FromHwnd,结果是在取得Graphic的时候出现运行时错误,更别说取得图片区域了。至于其它方法,没想也不想去想了。

另一个方法,如果只是想在图片上画一些文字,那么为什么不直接从PictureBox下手呢?重载它的OnPaint方法,绘制我们的文字不就行了吗?背景还是保持原来的不动。这个想法还是很不错的,而且代码也简单。最后结果也非常不错。

using  System;
using  System.Collections;
using  System.ComponentModel;
using  System.Drawing;
using  System.Data;
using  System.Windows.Forms;

namespace  Webb.InstantReplay.PublicControls.UIControls
{
    
/// <summary>
    
/// Summary description for TransparentLabel2.
    
/// </summary>

    public class TransparentLabel2 : System.Windows.Forms.PictureBox
    
{
        
//Fields
        private Point _Location = new Point(0,0);
        
//Properties
        public Point TextLocation
        
{
            
get
            
{
                
return this._Location;
            }

            
set
            
{
                
this._Location = value;
            }

        }

        [Browsable(
true)]
        
new public string Text
        
{
            
get{return base.Text;}
            
set{base.Text = value;}
        }

        [Browsable(
true)]
        
new public Font Font
        
{
            
get{return base.Font;}
            
set{base.Font = value;}
        }

        
//
        public TransparentLabel2()
        
{
        }


        
protected override void OnPaint(PaintEventArgs e)
        
{
            
base.OnPaint (e);
            SizeF m_size 
= e.Graphics.MeasureString(this.Text,this.Font);
            e.Graphics.DrawString(
this.Text,this.Font,Brushes.Black,new RectangleF(this._Location,m_size));
        }

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值