• 如何让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));
            }

        }

    }

  • 相关阅读:
    数据绑定表达式语法(Eval,Bind区别)
    使用博客园的第一件事 自定义主题
    sql2000 跨服务器复制表数据
    使用UpdatePanel 局部刷新出现中文乱码的解决方法!!
    MMC不能打开文件MSC文件
    sql 日期 、时间相关
    loaded AS2 swf call function in AS3 holder
    Rewrite the master page form action attribute in asp.net 2.0
    100万个不重复的8位的随机数
    flash 中实现斜切变型
  • 原文地址:https://www.cnblogs.com/WuCountry/p/797907.html
Copyright © 2020-2023  润新知