Drawing rotated text…

A customer emailed me today (via the VB FAQ blog) with a question; “how can I output text at different angles, to write the cardinal points around a compass for example…” so I decided to fire up a quick sample

 Public Enum Direction As Integer
  N = 0
  NW = 1
  W = 2
  SW = 3
  S = 4
  SE = 5
  E = 6
  NE = 7
End Enum
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
  Dim bounds As Rectangle
  Dim g As Graphics
  Dim rotation As Single = 0
  g = e.Graphics
  bounds = New Rectangle(50, 50, Me.Width - 100, Me.Height - 100)
  Dim rect As System.Drawing.RectangleF
  g.DrawEllipse(Pens.Black, bounds)
  Dim myMatrix As Drawing2D.Matrix
  Dim sf As New StringFormat(StringFormatFlags.NoWrap)
  sf.Alignment = StringAlignment.Center
  myMatrix = g.Transform()
  rect = New System.Drawing.RectangleF(bounds.X, bounds.Y, bounds.Width, bounds.Height)
  For i As Integer = 0 To 7
    If i > 0 Then
      myMatrix.RotateAt(45, New PointF(Me.Width / 2, Me.Height / 2), Drawing.Drawing2D.MatrixOrder.Append)
      g.Transform = myMatrix
    End If
    Dim directionString As String
    directionString = System.Enum.GetName(GetType(Direction), i)
    g.DrawString(directionString, New Font("Arial", 12, FontStyle.Bold), Brushes.Black, rect, sf)
End Sub

If you want to try this code, create a new Windows Forms application in VS.NET 2003, and paste this code into your Form, after the “Windows Form Designer generated code” region.

The result will be an image like this:

If you are looking for more info on GDI+ drawing in VB.NET, I’d suggest my article on the subject ๐Ÿ™‚ and there is a good book available from AW

Update: Ugh… I messed up the directions… and didn’t even notice (thanks Edward!!)

The enum should be

ยทยทยทยทยทยทยท N = 0
ยทยทยทยทยทยทยท NE = 1
ยทยทยทยทยทยทยทยทE = 2
ยทยทยทยทยทยทยท SE = 3
ยทยทยทยทยทยทยท S = 4
ยทยทยทยทยทยทยท SW = 5
ยทยทยทยทยทยทยทยทW = 6
ยทยทยทยทยทยทยท NW = 7

Author: Duncan Mackenzie

I'm the Developer Lead for the Channel 9 team, formerly worked on MSDN as a developer, content strategist and author.

9 thoughts on “Drawing rotated text…”

  1. sir/madam
    i want a method so that i can convert a text page into an excel form and also able to run macros on that sheet as in excel

  2. hello,

    how can i connect my report from access to visual basic?and how to add item from a textbox from form1 to a combobox of form2?

    gud pm…

Leave a Reply to kim Cancel reply