您的位置:首页 > 编程语言 > C#

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

2014-02-20 10:25 344 查看
本文描述如何在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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: