Jump to content
xisto Community
Sign in to follow this  
tansqrx

VB.NET: Rotating Label & Angled Text Control Write text at any angle with this

Recommended Posts

Language: Visual Basic.NET 2003

 

Description: Standard Windows Form Label control capable of rotating its text from -360 to 360 degrees. This control has two reference modes, center and quadrant.

 

Sample:Posted Image

 

In a recent programming endeavor I had the need to have text displayed in the vertical position. As usual, what I thought would be a 10 min solution became a 3 day journey. I just assumed that the standard windows form label control had a build in property that would determine the orientation. Once I looked and Googled for the property I soon found I was out of luck. I never did find an all inclusive answer to my problem, although I found several good leads that lead me in the right direction. With the lack of answers I decided to write this tutorial to show how to create a label control that will rotate on any angle.

As with many problems of this type, the best way to handle the problem is to create your own custom control. In this case the rotating label will inherit all of it attributes from the existing label control. The first step is to create a new Windows Control Library project and name it Rotating_Label_Control as shown in Figure 1.

 

Posted Image

Figure 1 - Create Project

 

The second step is to create the structure of the class. As a general rule of thumb I always include Option Strict On and Option Explicit On .

 

Option Strict OnOption Explicit On

Next change the class name and Inherit the System.Windows.Forms.Label namespace

 

Public Class Rotating_LabelInherits System.Windows.Forms.LabelEnd Class

Posted Image

Figure 2 - Select override OnPaint

 

There is no need to keep the Windows Form Designer generated code so that can be safely deleted. The place that we will insert the rotation is in the OnPaint function. Visual Studio gives us an easy way of doing this. From the drop down menus just below the file tabs, select (Overrides) and OnPaint as shown in figure 2. The designer produces the following code.

 

Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)End Sub

Also at this step add two properties. These will show up under the Misc. Section in the form designer. The first property is the rotation angle that the text should take. This property should be self explanatory. The second is the mode which the text should be displayed as. The mode is set as a boolean as to use self-centering or quadrant based alignment. Centering text rotates the text around the center of the text field and acts like center justify in a word processor. This is most likely the preferred method if the text will be dynamically changed during runtime. The second method attaches the text to the label container in one of the corners, depending on the rotation angle. This acts as a weird left (right, top, or bottom depending which quadrant you are in) justify in a word processor. The purpose of this mode is mostly for design time labels. For example, if I have several labels tilted on a -90 degree angle (vertical) with different text lengths I would prefer the quadrant mode because the text does not grow from the center and I can align all of the labels from the bottom left corner. Below is the code to add for the two properties. We will encounter both in the OnPaint method.

 

'Priviate VariablesPrivate _rotationAngle As IntegerPrivate _quadrantMode As Boolean'PropertiesPublic Property rotationAngle() As Integer  Get    Return _rotationAngle  End Get  Set(ByVal Value As Integer)    _rotationAngle = Value    MyBase.Refresh()  End SetEnd PropertyPublic Property quadrantMode() As Boolean  Get    Return _quadrantMode  End Get  Set(ByVal Value As Boolean)    _quadrantMode = Value    MyBase.Refresh()  End SetEnd Property

Now we will move on to the OnPaint override. First we find out what the text area dimensions are. This is not the dimensions of the label control but the dimensions of the actual text field. Next is a variable that converts the rotated angle into radians which is used for the trig functions in quadrant mode. Lastly is a variable that captures the foreground color as a brush. The DrawString function takes a brush but the font property only offers a dwawing.color object.

 

'variables to capture the size of the text areaDim width As Double = e.Graphics.MeasureString(Text, Me.Font).WidthDim height As Double = e.Graphics.MeasureString(Text, Me.Font).Height'convert the rotation angle into radians for trig functionsDim angleRadian As Double = ((_rotationAngle Mod 360) / 180) * Math.PI'capture the forground color as a brushDim myBrush As Brush = New SolidBrush(Me.ForeColor)

Next is a selector for either center or quadrant modes in the form of a if statement. First we will tackle the quadrant mode. To make a rotation, two operations must occur, the rotation and adjustment on the x,y axis for the rotation. If only the rotation occurs a clipping of the text occurs. In the simplest case of quadrant I, the bottom left part of the string is chopped off. To compensate I moved the sting to the right the distance of the clipping. The clipping distance can be found by using trig as the label container and string rectangle forms a triangle. I will not go much further into this as I'm still looking at several sheets of green engineering graph paper and hoping not to relive that experience again for quite some time. The appropriate correction is made for each quadrant in the if / ifelse structure.

 

If _quadrantMode = True Then'Quad IIf (_rotationAngle >= 0 AndAlso _rotationAngle < 90) Or (_rotationAngle < -270 AndAlso _rotationAngle >= -360) Thene.Graphics.TranslateTransform(CInt(Math.Sin(angleRadian) * height), 0)'Quad IIElseIf (_rotationAngle >= 90 AndAlso _rotationAngle < 180) Or (_rotationAngle < -180 AndAlso _rotationAngle >= -270) Thene.Graphics.TranslateTransform(ClientRectangle.Width, CInt(height - (Math.Sin(angleRadian) * height)))'Quad IIIElseIf (_rotationAngle >= 180 AndAlso _rotationAngle < 270) Or (_rotationAngle < -90 AndAlso _rotationAngle >= -180) Thene.Graphics.TranslateTransform(ClientRectangle.Width + CInt(Math.Sin(angleRadian) * height), ClientRectangle.Height)Else 'Quad IVe.Graphics.TranslateTransform(0, ClientRectangle.Height - CInt(Math.Cos(angleRadian) * height))End If

I can not take credit for the center mode as I browed it from Chester Ragel who has an article on The Code Project Website [http://forums.xisto.com/no_longer_exists/]. The borrowed code is written in C# and actually has more functionality than my code as it also produces arcs and circles. I understand the code but I will not explain it here

 

Else 'Center Modee.Graphics.TranslateTransform(CInt((ClientRectangle.Width + (height * Math.Sin(angleRadian)) - (width * Math.Cos(angleRadian))) / 2), CInt((ClientRectangle.Height - (height * Math.Cos(angleRadian)) - (width * Math.Sin(angleRadian))) / 2))End If

Finially the code is ended with the rotation and writing of the string.

 

'Make the actual rotation,and draw the stringe.Graphics.RotateTransform(CInt(_rotationAngle))e.Graphics.DrawString(Me.Text, Me.Font, myBrush, 0, 0)e.Graphics.ResetTransform()

Posted Image

Figure 3 - Adding a Control

 

Once the code is complete, compile it and you should get an error stating that an object with the type of class library can not be started directly. This is fine and indicated that the project DLL was complied successfully. From another project in which you want to use the new control in, go to the designer view. Right click in a tab and select add/remove items as shown in figure 3. Go to browse and go to the /bin directory of the Rotating_Label project. Select Vertical_Label_Control.dll and click OK. You should not see the control displayed in the tab. When needed simply add the control just like the regular label, set the properties, and your all done.

A .zip file with the control source and example project is included below.

Edited by microscopic^earthling (see edit history)

Share this post


Link to post
Share on other sites

Great job there tansgrx :lol: Moved to tutorials section. Are you good with GDI+ ?? I'm trying to design an opensource alternative for common charting control, i.e. design a freeware opensource class library which will allow you to draw excel like charts in your windows app in a jiffy. Are you interested in joining hands with me ? I'm infact trying to design a whole bunch of such utilitirian controls - to facilitate different aspects of vb & c# coding. Let me know..

Share this post


Link to post
Share on other sites

I wish I could help but I know absloutly nothing about GDI+, This is actually my next step in programming. The reason that I needed the rotating text was because I wanted to put headers on a datagrid. I would eventually like to make a control that looks like an accounting header for the datagrid, the one where the text is at a -60 degree angle with alternating colors.At any rate keep me informed on your charting effort, I might have a need for in in the not so distant future.

Share this post


Link to post
Share on other sites

Its actually not that bad. I have only been programming VB.NET for about 10 months now so it can't be that advanced. Of course I'm dealing with threading, datagrids, and the lifespan of classes right now so my perspective of advanced maybe relitive. If you have any questions feel free to post them and I'll see what I can do. The basics are that this control is a customized user control that overrides the OnPaint method. Don't worry about the complicted math involved, just copy and paste. I've had more math than a human should have to endure and it took me several hours to figure out what I had to do (damn trig identies).

Share this post


Link to post
Share on other sites

Thanks a lot for this tool.I tried the thing in Visual Basic Express Edition. It didn't work. I couldn't build a usercontrol with the given code 'cause the class yould not inherit the lable-class but only the usercontrol-class.I then put the code in a normal class-library. After changing the setting AutoSize to false, it worked perfectly.Thanks again

Share this post


Link to post
Share on other sites

Line control

VB.NET: Rotating Label & Angled Text Control

 

Hi,I need about the same thing for a line control.

I need lines to be drawn on my form between two points as I click on those points.The problem is there is no line control in C# so I am trying to create a UserControl with the size and location I need for my line.Size and location depend on where those points are located.Does anyone have an idea how I could do this.Am I missing somethig??

Thanx in advance for any help :)

 

-reply by Peter

Share this post


Link to post
Share on other sites

I have created onne user control and included it in my application. But now I want to move it at runtime. how can i do that. Please help me.

VB.NET: Rotating Label & Angled Text Control

 

In my user control I have included 1 label and 1 toolbar control. I have added this user control in my application. But now I want it to move at run time. Please help me out.

 

 

 

-question by Prajakta

Share this post


Link to post
Share on other sites

how to open an exe file in asp.net

VB.NET: Rotating Label & Angled Text Control

 

Dear sir / madam,

 

How to open an .Exe file in web forms (asp.Net)

 

Thanking sir

 

 

-reply by KPREDDY

Share this post


Link to post
Share on other sites
building image buttonVB.NET: Rotating Label & Angled Text Control

I am trying to build a Image button user control.

it should have the property to change the image and text

can any one  tell me how to set the properties

-reply by pradeep kumar

Share this post


Link to post
Share on other sites
about the vb.net form rotationVB.NET: Rotating Label & Angled Text Control

tell me how can I rotate a form in VB.Net through vertical position to horizontal position

-reply by gagan deep singh

Share this post


Link to post
Share on other sites
ASp.net->microsoft visual studio 2008VB.NET: Rotating Label & Angled Text Control

Hello,

In ASp.Net->microsoft visual studio 2008,

1] There is no Position option for label control in Format menu.

2]So its not possible to make position of label to absolute and because of this label control can not be moved.

3] can any one give me solution how to move label control on form in asp.Net?

Share this post


Link to post
Share on other sites
Text displaying Twice?VB.NET: Rotating Label & Angled Text Control

I am using VS 2008 to create the custom user control and following your instructions the control works and is only suffering one unexpected issue.  The text is showing not only rotated but it's also showing normally so the text is in the label twice?

Any thoughts? 

-question by Christopher

 

Share this post


Link to post
Share on other sites
animating a stringVB.NET: Rotating Label & Angled Text Control

how can I make animation of string using visual studio 2008.

how to make my on-screen keyboard response to any key press from my keyboard using vb 2008.

 creating games using vb 2008?

-question by umar abubakar

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.