|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Services
Chapters
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
IntroductionThis article describes how to create a custom vertical label user control in C#.NET. The user control provides drawing of text from top or from bottom. This article is a derivation of Raman Tayal's Vertical Label Control in VB.NET. I just translated his work to C# and added the functionality of drawing the text starting from bottom. BackgroundOn one of my projects, I need a label control that can display text vertically. I encountered Raman Tayal's Vertical Label Control in VB.NET and translated it to C#. But I need additional functionality of drawing text starting from the top, so I just added the functionality. This control has been useful to me and I hope others would find it useful too. Using the codeThe code provided is a class that creates a dll that can be added as item in Toolbox of Windows Forms designer. The class used the following namespaces: using System;
using System.ComponentModel;
using System.Drawing;
CodeThe part of the code that really does the job is the override for protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
float vlblControlWidth;
float vlblControlHeight;
float vlblTransformX;
float vlblTransformY;
Color controlBackColor = BackColor;
Pen labelBorderPen = new Pen(controlBackColor, 0);
SolidBrush 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);
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);
}
}
As you can see, I have an When the value of When the value of The On the screenshot that I provided, I deliberately changed the color of the background of the vertical label to show the anchor on where the control starts drawing the text. Points of InterestSince this is my first time to write a program using GDI+, I tried to do it using trial and error but it was frustrating at first, until I found a nice article on how to use the HistoryJuly 27, 2007. Initial Version.
|
||||||||||||||||||||||