Draw Rainbow Text In PictureBox/Form

The following example will show you how to print text in picture box,
and choose different color for every word or every character.
To draw the strings on your Form, simply change all the appearances of "Picture1" in the code with "Form1".

Preparations

Add 1 Picture Box , 1 Label and 1 Command Button to your form.

Form Code

' strWidth holds the current string width, so we
' will know in what X coordinate we will print
' the next characters

Dim strWidth As Long
' The space between characters
Const CharSpace = 5
' The space between lines
Dim LineSpace As Long
' Holds the current line
Dim CurLine As Integer


Public Sub RainbowText(text As String, colour As OLE_COLOR, Line As Integer)
    ' if it's new line, set the x position back to 0
    If CurLine <> Line Then
        CurLine = Line
        strWidth = 0
    End If
   
    ' set the text position
    Picture1.CurrentX = strWidth
    Picture1.CurrentY = (Line - 1) * LineSpace
    ' set the text color, and print it.
    Picture1.ForeColor = colour
    Picture1.Print text
   
    ' using Label1 we will measure the current text width
    Label1 = text
    strWidth = strWidth + Label1.Width + Char
End Sub

Private Sub Command1_Click()
    ' to draw string on the picture box, call the
    ' RainbowText sub with the following parameters:
    ' the string to draw, the color of the string, the line
    Call RainbowText("He", vbRed, 1)
    Call RainbowText("llo", vbGreen, 1)
    Call RainbowText("W", vbYellow, 2)
    Call RainbowText("orld", vbBlack, 2)
End Sub

Private Sub Form_Load()
    ' set the font properties
    Picture1.FontName = "Arial"
    Picture1.FontSize = 20
    Picture1.FontBold = True
    Picture1.FontItalic = False
    Picture1.FontUnderline = False
    Picture1.FontStrikethru = False
   
    Label1.AutoSize = True
    Label1.Visible = False
   
    ' adjust the label font properties to be the same as the
    ' picture box font properties, so they both have the same
    ' string width and height

    Label1.Font = Picture1.Font
    Label1.FontName = Picture1.FontName
    Label1.FontBold = Picture1.FontBold
    Label1.FontItalic = Picture1.FontItalic
    Label1.FontSize = Picture1.FontSize
    Label1.FontStrikethru = Picture1.FontStrikethru
    Label1.FontUnderline = Picture1.FontUnderline
   
    ' enter sample line to the label to check the height of the text
    Label1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    ' add more space to the line (10)
    LineSpace = Label1.Height + 10
   
    strWidth = 0
    CurLine = 1
   
End Sub

Go Back