C#实现透明背景的垂直Label控件

本文描述如何在c#中创建一个透明背景色的垂直label用户控件。该用户控件允许你从底部或顶部开始绘制文字。

本文是Vertical Label Control in VB.NET的延续。其实,更准确的说,我是把他的工作翻译到C#中,并添加了从下向上显示文字的功能。另外,支持背景透明。


代码使用
本文中的源代码提供了一个类,并用它生成了一个dll,你可以添加为Windows Form设计器中Toolbox里的一个item。

控件代码

该类使用了以下命名空间:

using System;
using System.ComponentModel;
using System.Drawing;
using randz.CustomControls;

控件的代码中,起实际作用的是OnPaint事件的重载:

protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
    float vlblControlWidth;
    float vlblControlHeight;
    float vlblTransformX;
    float vlblTransformY;

    Color controlBackColor = BackColor;
    Pen labelBorderPen;
    SolidBrush labelBackColorBrush;

    if (_transparentBG)
    {
        labelBorderPen = new Pen(Color.Empty, 0);
        labelBackColorBrush = new SolidBrush(Color.Empty);
    }
    else
    {
        labelBorderPen = new Pen(controlBackColor, 0);
        labelBackColorBrush = new SolidBrush(controlBackColor);
    }
    
    SolidBrush labelForeColorBrush = new SolidBrush(base.ForeColor);
    base.OnPaint(e);
    vlblControlWidth = this.Size.Width;
    vlblControlHeight = this.Size.Height;
    e.Graphics.DrawRectangle(labelBorderPen, 0, 0, vlblControlWidth, vlblControlHeight);
    e.Graphics.FillRectangle(labelBackColorBrush, 0, 0, vlblControlWidth, vlblControlHeight);
    e.Graphics.TextRenderingHint = this._renderMode;
    e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    
    if (this.TextDrawMode == DrawMode.BottomUp)
    {
        vlblTransformX = 0;
        vlblTransformY = vlblControlHeight;
        e.Graphics.TranslateTransform(vlblTransformX, vlblTransformY);
        e.Graphics.RotateTransform(270);
        e.Graphics.DrawString(labelText, Font, labelForeColorBrush, 0, 0);
    }
    else
    {
        vlblTransformX = vlblControlWidth;
        vlblTransformY = vlblControlHeight;
        e.Graphics.TranslateTransform(vlblControlWidth, 0);
        e.Graphics.RotateTransform(90);
        e.Graphics.DrawString(labelText, Font, labelForeColorBrush, 0, 0, StringFormat.GenericTypographic);
    }            
}



你可以看到代码里面的if (this.TextDrawMode == DrawMode.BottomUp),它是决定从底部向上,还是从顶部向下来绘制文字。

TextDrawMode是一个额外的属性,你可以在设计代码的时候,设置它。

注意,有一个布尔型的变量TransparentBackground,如果它被设置为true,Brush颜色会被设置成Color.Empty

为了让控件透明,我重载了下面的代码:

protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= 0x20;  // Turn on WS_EX_TRANSPARENT
        return cp;
    }
}

资源链接http://www.codeproject.com/Articles/19774/Extended-Vertical-Label-Control-in-C-NET
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值