Thursday, November 19, 2009

Draw rotated text in VB/ASP.NET using the Matrix class

While working on 2D drawings in VB.NET, you might find yourself in a situation where you may want to rotate a text or any other object on the drawing canvas. I discovered this technique when I was trying to draw my text vertically from bottom to top and the System.Drawing.StringFormat class’s built in vertical text format would only support top to bottom layout. Then I discovered the System.Drawing.Drawing2D.Matrix class which is used for geometric transformation. Using the Matrix class you can rotate the drawing canvas to any desired angle, draw the text/object and then rotate it back to the original position.

Example of rotated text:
Rotated text in VB .NET

I have implemented the drawing by using ASP.NET web application where the drawing is generated by an aspx page. To view the image in web browser, you just need to create an HTML image tag on a new page and set the image source(src) to the .aspx file. The .aspx file code to generate a sample PNG file is given below. The main functionality for rotating the text is implemented in the RotateString subroutine which is provided with the text, rotation angle, and the x and y coordinates.

Imports System.Drawing
Imports System.IO
Imports System.Drawing.Drawing2D

Partial Public Class TextImageDraw
    Inherits System.Web.UI.Page

    'Dimensions of the bitmap
    Const DRAWING_HEIGHT As Integer = 300
    Const DRAWING_WIDTH As Integer = 300

    Dim bitmap As New Bitmap(DRAWING_WIDTH, DRAWING_HEIGHT)
    Dim myDrawing As Graphics = Graphics.FromImage(bitmap)

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim myDrawingBackgroundColor As New SolidBrush(Color.AliceBlue)
        'Fill Drawing Background
        myDrawing.FillRectangle(myDrawingBackgroundColor, 0, 0, DRAWING_WIDTH, DRAWING_HEIGHT)

        myDrawing.TextRenderingHint = Text.TextRenderingHint.AntiAlias

        Dim myText As String = ""

        'Text Rotation Cordinates
        Dim xCordinate As Integer = DRAWING_WIDTH / 2
        Dim yCordinate As Integer = DRAWING_HEIGHT / 2

        'Draw Rotation Center
        myDrawing.DrawEllipse(Pens.Black, New Rectangle(xCordinate - 1, yCordinate - 1, 3, 3))

        'Draw Header Text
        Dim headingText As String = "Rotating Text"
        Dim headingFont As Font = New Font("arial", FontSize.XLarge, FontStyle.Regular)
        Dim headingTextWidth As Double = myDrawing.MeasureString(headingText, headingFont).Width
        Dim headingTextHeight As Double = myDrawing.MeasureString(headingText, headingFont).Height
        myDrawing.DrawString(headingText, headingFont, Brushes.Red, _
                             (DRAWING_WIDTH - headingTextWidth) / 2, 2)

        'Draw Text in 360 degrees with 30 degree interval
        For angle = 0 To 330 Step 30
            RotateString(myText, angle, xCordinate, yCordinate)

        'Draw Footer Text
        myDrawing.DrawString(headingText, headingFont, Brushes.Red, _
                            (DRAWING_WIDTH - headingTextWidth) / 2, _
                            DRAWING_HEIGHT - headingTextHeight - 2)

        'Set smoothing mode for the drawing to Anti-alias
        myDrawing.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias

        'Write the image to browser...
        Response.ContentType = "image/png"
        Dim mem As New MemoryStream()
        bitmap.Save(mem, System.Drawing.Imaging.ImageFormat.Png)
    End Sub

    Private Sub RotateString(ByVal Text As String, ByVal angle As Integer, _
                             ByVal x As Integer, ByVal y As Integer)
        Dim myFont As Font = New Font("arial", FontSize.XLarge, FontStyle.Regular)
        Dim myColor As SolidBrush = New SolidBrush(Color.Black)
        ' Make a rotation matrix
        Dim myMatrix As New Matrix
        myMatrix.RotateAt(angle * -1, New Point(x, y)) 'Rotate drawing
        myDrawing.Transform = myMatrix
        myDrawing.DrawString(Text, myFont, myColor, x, y) 'Draw the text string
        myMatrix.RotateAt(angle, New Point(x, y)) 'Rotate back
        myDrawing.Transform = myMatrix
    End Sub

End Class

You can just copy the RotateString subroutine to your code and pass the Graphics class object along with other parameters to draw the rotated string on it.


  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

  2. mytectra placement Portal is a Web based portal brings Potentials Employers and myTectra Candidates on a common platform for placement assistance.

  3. Guaranteed #1 Search Engine Ranking Supreme Free Viral Traffic Join Now Get Millions Of Hits Free To Your Site/Blog!

    PornKings Adult Shopping Backlinks-Shopping Mega Store Legendary Stars As Stormy Daniels,Shawna Edwards,Jenna Jamison-New Adult Stars Movies,Adult Toys,Enhancers,Merchandise-More !

    Hits Express Rotator System Do You Need Visitors to Your Website or Affiliate Program? If your looking to gain more visitors to your website Hits Express is your answer. With our program your site is being shown to people all over the world 24/7 365 days a year!

    PAYDIR Free For All Forum Portal Search Engine Crawled Network PR10 Ranking Information Forum XXX!

    FreeLinkExchanges Be Seen In 12 Nations 312 Sites Over 30 Millions Viewers Monthly Buy Featured Link Now With 150 Search Engines Crawling The Network!

    How do I get guaranteed traffic? When someone signs up from your site, they must first click on your classified ad which will open a new window leading to your main website. They will have to wait a few seconds for the code to appear on a separate frame at the top of the screen reach millions free now!

    Blast Your Ad to Over 23,000 Opt-in Prospects at ShowMyLinks Submit Your Solo Email Ad to All Showmylinks Members GET YOUR TEXT LINK ADs LISTED 100% FREE FOR LIFE PLUS EARN MONEY TO YOUR PAYPAL!!

    Adult Store Empires Backlinks Resources Search Engine XXX!

    GET YOUR OWN MONEY-MAKING AD BOARD -- Integrating Text ad, Banner Ad and Email Ad into one Portal Make Money Fast With Your Paypal Reach Million Dollars In A Year Fast !

    Full Length Homemade Videos Watch real people's private home sex videos. Forget about those shitty 1-2 minute clips, these are all high quality full length videos! 40+ Bonus Sites You will also get full access to the entire reelpass network of sites which features over 40+ awesome movie sites, 1000's of movies and pictures to download! Download, Burn & Share Not only do you get to watch all our movies, you can also download every single one and save it forever, burn them to dvd or share with friends!!


Thanks a lot for your valuable comments :)