Monday, July 19, 2010

Gradient Form - Function

A simple function to make your form background gradient.

First you need to :

Import System.Drawing.Drawing2D

In the method New() or Load :



' Optimize Painting.
  SetStyle(ControlStyles.AllPaintingInWmPaint Or _
              ControlStyles.DoubleBuffer Or _
              ControlStyles.ResizeRedraw Or _
              ControlStyles.UserPaint, _
              True)

In the OnPaint Method :



Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
 
        'Creating a new Rectangle as similar width and height of the base form 
        Dim oRAngle As Rectangle = New Rectangle(0, 0, Me.Width, Me.Height)
 
        'Creating a new Gradient style brush.
        'Change the colors here to get different color combination.
        '"Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal" can be changed accordingly to get different styles like
        'ForwardDiagonal, Horizontal, Vertical.
        Dim oGradientBrush As Brush = New Drawing.Drawing2D.LinearGradientBrush(oRAngle, Color.Silver, Color.WhiteSmoke, Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal)
 
        'With the help of fillrectangle function drawing rectangle in to form
        e.Graphics.FillRectangle(oGradientBrush, oRAngle)
 
End Sub


Or if you want a function to use for your controls :



Private Function DrawGradientBackground(ByVal Ctrl As Control, ByVal color1 As Color, ByVal color2 As Color, ByVal mode As System.Drawing.Drawing2D.LinearGradientMode) As Boolean
    Try
        Dim a As New System.Drawing.Drawing2D.LinearGradientBrush(New RectangleF(0, 0, Ctrl.Width, Ctrl.Height), color1, color2, mode)
        Dim g As Graphics = Ctrl.CreateGraphics
        g.FillRectangle(a, New RectangleF(0, 0, Ctrl.Width, Ctrl.Height))
        g.Dispose()
        Return True
    Catch ex As Exception
        MsgBox("Error Creating Gradient!" + Environment.NewLine + ex.Message)
        Return False
    End Try
End Function

No comments:

Post a Comment