Wu.Country@侠缘

勤学似春起之苗,不见其增,日有所长; 辍学如磨刀之石,不见其损,日所有亏!

导航

如何让Label的背景透明(小技巧)

问题很简单不是吗,把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));
        }

    }

}

 

 

posted on 2007-06-27 16:57  Wu.Country@侠缘  阅读(19034)  评论(5编辑  收藏  举报