I found the code below to create a class for a rotated label.
Not sure where I found it or who wrote it.
I'm still new with VB.NET.
The code works great until you try to rotate the text more than 90 degrees.
Then the text is not in the control anymore.
I would like to be able to rotate the text to any angle but have not been able to figure out what I need to change.
Any help would appreciated.
Jim
Imports System.Drawing.Drawing2D
Public Class New_Rotated_Label
Inherits Control
Private TextRectangle As Rectangle
Private Mtx As Matrix
Private gp As GraphicsPath
Private _TextRotation As Integer = 45
Public Property TextRotation As Integer
Get
Return _TextRotation
End Get
Set(ByVal value As Integer)
If value > 359 Then value = 359
If value < 0 Then value = 0
_TextRotation = value
SetRegion(Nothing, Nothing)
Me.Refresh()
End Set
End Property
Public Overrides Property Text As String
Get
Return MyBase.Text
End Get
Set(value As String)
MyBase.Text = value
Dim TextSize As Size = TextRenderer.MeasureText(value, Font)
TextRectangle = New Rectangle(New Point(0, 0), TextSize)
End Set
End Property
Public Sub New()
Me.SetStyle(ControlStyles.OptimizedDoubleBuffer Or ControlStyles.SupportsTransparentBackColor, True)
Me.SetStyle(ControlStyles.ResizeRedraw Or ControlStyles.UserPaint, True)
Me.SetStyle(ControlStyles.Selectable, False)
Dim Y As Integer = Me.Height
TextRectangle = New Rectangle(0, 0, Width, Height)
Region = New Region
End Sub
Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
MyBase.OnTextChanged(e)
Me.Refresh()
End Sub
Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs)
e.Graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
e.Graphics.Transform = Mtx
Using Brsh As New SolidBrush(ForeColor)
e.Graphics.DrawString(Text, Font, Brsh, TextRectangle.Location)
End Using
End Sub
Private Sub SetRegion(sender As Object, e As EventArgs) Handles Me.Resize, Me.TextChanged, Me.FontChanged
If Mtx IsNot Nothing Then Mtx.Dispose()
Mtx = New Matrix
If gp IsNot Nothing Then gp.Dispose()
gp = New GraphicsPath
gp.AddRectangle(TextRectangle)
Mtx.Translate(CInt(TextRectangle.Height * Math.Sin(TextRotation / (360 / Math.PI))), 0)
Mtx.Rotate(TextRotation)
gp.Transform(Mtx)
If Region IsNot Nothing Then Region.Dispose()
Region = New Region(gp)
End Sub
End Class
What I have tried:
Tried changing the New Rectangle command to set the Y coordinate, but that doesn't work.