How to draw GDI text with gradient effect in vb.net

Following example show how to add gradient effect to text in vb.net :

 Private Sub DrawGradientText()
        Dim textSize As SizeF
        Dim g As Graphics
        Dim myBrush As Brush
        Dim gradientRectangle As RectangleF

        Dim fontconverter As New FontConverter
        Dim myFont As Font
        myFont = fontconverter.ConvertFromString(txtFont.Text)

        Dim PrimaryColor As Color = lblPrimaryColor.BackColor
        Dim SecondaryColor As Color = lblSecondaryColor.BackColor

        ' Create a Graphics object from the picture box & clear it.
        g = PictureBox1.CreateGraphics()
        g.Clear(Color.White)

        ' Find the Size required to draw the Sample Text.
        textSize = g.MeasureString(Me.txtText.Text, myFont)

        ' Create a Diagonal Gradient LinearGradientBrush.
        gradientRectangle = New RectangleF(New PointF(0, 0), textSize)
        myBrush = New LinearGradientBrush(gradientRectangle, PrimaryColor, _
        SecondaryColor, LinearGradientMode.ForwardDiagonal)

        ' Draw the text.
        g.DrawString(txtText.Text, myFont, myBrush, _
        (PictureBox1.Width - textSize.Width) / 2, _
        (PictureBox1.Height - textSize.Height) / 2)
    End Sub

4 thoughts on “How to draw GDI text with gradient effect in vb.net”

  1. I’ve a doubt about your code. I made a VB2010 application using the code above but a weird thing happened. When I run the application and change the font size to 20 (it started with the value 8) the picturebox is not affected, in other words, it’s nothing identifying the change of the font size somewhere in the code, even if I insert a line after the fontsize change to perform the sub again. By the way, it’s working but the fontsize in the picturebox stays with heigth 8.

    1. Hello Vitor
      Can you send me the your code sample so that i can review your code and solve your problem

      thanks

  2. Oh, I already figured out what was wrong with my application, but I’m thankfull for any attention. If someone more diseres know about this supposed error, it’s in this patch

    myFont = fontconverter.ConvertFromString(txtFont.Text), myfont needs to receive a string
    font this way “FontName; fontsize pt” (realize that used semicolon to separate fontname from
    fontsize), the error was happening because I joined the strings using comma, and I wasn’t
    respection the spaces in the string. That’s all. Thank you guy for the cool code lines. I hope to
    see more codes like this again.

Comments are closed.