Wednesday, April 25, 2007

Gradient Colors in GDI+

In programming, gradient is a transition color from a start point to end point. In my past with VB6, I have to modify each pixel to make a gradient within a container. Now with VB2005, you can make a gradient on a surface with a few lines of codes.

To creating a gradient, we need GradientBrush object. There are 2 types of them: LinearGradientBrush and PathGradientBrush. I'll explain those two in next section.

The LinearGradientBrush

As it names, this method creates a linear gradient color, which means creates 1 way directional gradient. The directional depends on where do you set starting and destination point. There are 4 default destinations for this method which are: Horizontal, Vertical, Diagonal Forward, and Diagonal Backward.

Example:
Linear Gradient with Horizontal direction, from Red to Blue and fill entire form.


Code

Using lgb As New LinearGradientBrush(Me.ClientRectangle, Color.Red, Color.Blue, LinearGradientMode.Horizontal)

e.Graphics.FillRectangle(lgb, Me.ClientRectangle)

End Using


The PathGradientBrush

Unlike LinearGradientBrush, the PathGradientBrush method has different way to call. First, it needs a GraphicsPath object.

GraphicsPath may be composed of any number of figures (subpaths). Each figure is either composed of a sequence of connected lines and curves or a geometric shape primitive. The starting point of a figure is the first point in the sequence of connected lines and curves. The ending point is the last point in the sequence. The starting and ending points of a geometric shape primitive are defined by the primitive specification. (Source: MSDN Library, December 2006)

The PathGradientBrush color transition is different from LinearGradientBrush. It focused on a center and spread to the edges of GraphicsPath. If you want to modifiy the center coordinate, use CenterPoint property. Another important property is FocusScale, which determine how strong the transition from starting color to destination color. Also, PathGradientBrush allow you to make multiple color transition in one surface.

Example:
Path Gradient with Red as center color and 3 colors (Blue,Yellow and Green) as surround colors.


Code

Using pth As New GraphicsPath

pth.AddRectangle(Me.ClientRectangle)

Using pgb As New PathGradientBrush(pth)

pgb.CenterColor = Color.Red
pgb.SurroundColors = New Color() {Color.Blue, Color.Yellow, Color.Green}

e.Graphics.FillPath(pgb, pth)
End Using
End Using

No comments: