What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleDisplay rotated text on top of a PictureBox
DescriptionThis example shows how to display rotated text on top of a PictureBox in Visual Basic 6. It uses the CreateFont API function to build the rotated font.
Keywordsrotated text, rotated font, CreateFont, PictureBox
Subroutine DrawRotatedText uses the CreateFont API function to make a rotated font. It selects the font into a device context (DC) and prints the text. It then deselects the font and calls DeleteObject to free its resources.
Private Sub DrawRotatedText(ByVal target As Object, _
    ByVal txt As String, _
    ByVal X As Single, ByVal Y As Single, _
    ByVal font_name As String, ByVal size As Long, _
    ByVal weight As Long, ByVal escapement As Long, _
    ByVal use_italic As Boolean, ByVal use_underline As _
        Boolean, _
    ByVal use_strikethrough As Boolean)

Const CLIP_LH_ANGLES = 16   ' Needed for tilted fonts.
Const PI = 3.14159625
Const PI_180 = PI / 180#

Dim newfont As Long
Dim oldfont As Long

    newfont = CreateFont(size, 0, _
        escapement, escapement, weight, _
        use_italic, use_underline, _
        use_strikethrough, 0, 0, _
        CLIP_LH_ANGLES, 0, 0, font_name)
    ' Select the new font.
    oldfont = SelectObject(target.hdc, newfont)

    ' Display the text.
    target.CurrentX = X
    target.CurrentY = Y
    target.Print txt

    ' Restore the original font.
    newfont = SelectObject(target.hdc, oldfont)

    ' Free font resources (important!)
    DeleteObject newfont
End Sub
When the form loads, the program calls DrawRotatedText to draw some text on its PictureBox.
Private Sub Form_Load()
Const PI = 3.14159265
Dim angle As Long

    ' Make the form fit the picture.
    Width = Width - ScaleWidth + Picture1.Width
    Height = Height - ScaleHeight + Picture1.Height
    Picture1.Move 0, 0

    ' Get the angle from the upper left to
    ' lower right corner.
    angle = 100 * 180 / PI * Atn(Picture1.ScaleHeight / _

    ' Draw the angled text.
    Picture1.AutoRedraw = True
    Picture1.ForeColor = vbRed
    DrawRotatedText Picture1, _
        "My Dog Snortimer", _
        1000, 500, _
        "Times New Roman", 40, 700, _
        angle, False, False, False

    ' Make the result permanent.
    Picture1.Picture = Picture1.Image
End Sub

My book Visual Basic Graphics Programming shows how to rotate, stretch, and compress fonts, and how to make text follow a path.

My book Custom Controls Library shows how to build custom controls that display rotated text and text that follows a path.

Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.