Gradient Brushes in GDI+


This article has been excerpted from book "Graphics Programming with GDI+".
 
Linear gradient brushes allow you to blend two colors together, generating an indefinite range of shades. The Blend class defines a custom falloff for the gradient.

In a gradient, we begin with a starting color and shift to an ending color, with gradual blending in the space between them. In addition to the starting and ending colors, we can specify the direction of the gradient. For example, Figure 4.12 starts with green in the left bottom corner and ends with red in the top right corner. (You may not notice these colors exactly in a black-and-white image.)

You can also specify a range for pattern repetition. For example, you can specify that the gradient will occur from point (0,0) to point (20, 20) and after that will repeat the same pattern, as in Figure 4.13.

 
Figure-4.12.jpg
 
FIGURE 4:12: A color gradient
 
Figure-4.13.jpg
 
FIGURE 4.13: A gradient pattern with pattern repetition

Linear Gradient Brushes

The LinearGradientBrush class has eight forms of overloaded constructors. Each constructor takes a starting point, an ending point and two gradient colors. The orientation and linear gradient mode are optional.

The following code snippet creates a linear gradient brush using the colors red and green.

Rectangle rect1 =
new Rectangle (20, 20, 50, 50);
LinearGradientBrush lgBrush = new LinearGradientBrush (rect1, Color.Red, Color.Green, LinearGradientMode.Horizontal);

 
Here the mode parameter is represented by the LinearGradientMode enumeration, which specifies the direction of a linear gradient. The members of the LinearGradientMode enumeration are described in Table 4.3.
 
Now let's look at the properties and methods of the LinearGradientBrush class, which are defined in Table 4.4 and 4.5 respectively.

Linear Gradient Brushes Example

 
Now let's create an application that uses linear gradient brushes. We create a Window application; add three label controls, a combo box, two text boxes, four buttons, and two check boxes. We also change the Text property and other properties of these controls. The final form looks like Figure 4.14.
 
The combo box will list the linear gradient modes. The Pick... buttons allow the user to pick starting and ending colors for the gradient process. The Other Rectangle check box uses a rectangle to specify the range of the gradient. We will discuss the Gamma Correction and Properties options later in this section.

TABLE 4.3: LinearGradientMode members
 
Member Description

BackwardDiagonal

Specifies a gradient from upper right to lower left.

ForwardDiagonal

Specifies a gradient from upper left to lower right.

Horizontal

Specifies a gradient from left to right.

Vertical

Specifies a gradient from top to bottom.


TABLE 4.4: LinearGradientBrush properties
  
 
Property Description

Blend

Represents the Blend object that specifies gradient position and factors.

GammaCorrection

Represents gamma correction. If it is enabled, the value is true; if not, it is false.

InterPolationColors

Represents a ColorBlend object that defines a multicolor gradient.

LinearColors

Represents the starting and ending colors of a gradient.

Rectangle

Returns a rectangle that defines the starting and ending points of a gradient.

Transform

Represents a Matrix object that defines the transformation.

WrapMode

Represents a WrapMode enumeration that indicates the wrap mode.


TABLE 4.5: LinearGradientBrush methods
 
Method Description

MultiplyTransform

Multiplies a Matrix object that represents the transformation.

ResetTransform

Reset the Transform property to identify.

RotateTransform

Rotates the transformation.

ScaleTransform

Scales the transformation.

SetSigmaBellShape

Creates a gradient falloff based on a bell-shaped curve.

TranslateTransform

Translates the transformation by the specified dimensions.


Figure 4.14.gif

 
FIGURE 4.14: Our linear gradient brush application

Next we add some class-level variable as follows:
 
        private LinearGradientBrush lgBrush = null;
        private LinearGradientMode mode =
        new LinearGradientMode();
        private Color startColor = Color.Red;
        private Color endColor = Color.Green;
 
After defining the variable, we add the code from Listing 4.11 on the form's load event handler. As the code shows, we add all gradient modes on the AddGradeintMode method. We also set the default background color of text boxes.

LISTING 4.11: Adding available linear gradient modes
 
private void Form1_Load (object sender, System.EventArgs e)
      {
             AddGradientMode();
             textBox1.BackColor = startColor;
             textBox2.BackColor = endColor;
      }

 
        private void AddGradientMode()
        {
            //Adds linear gradient mode styles to the combo box
             comboBox1.Items.Add(LinearGradientMode.BackwardDiagonal);
             comboBox1.Items.Add(LinearGradientMode.ForwardDiagonal);
             comboBox1.Items.Add(LinearGradientMode.Horizontal);
             comboBox1.Items.Add(LinearGradientMode.Vertical);
            comboBox1.Text = LinearGradientMode.BackwardDiagonal.ToString();
        }
 
Next we add code for the Pick... buttons, which allow the user to provide color selections for the starting and ending colors. We also set the color of relative text boxes, as shown in Listing 4.12.
 
LISTING 4.12: The pick button click event handler

 
        private void StartClrBtn_Click(object sender, System.EventArgs e)
        {
            //Use ColorDialog to select a color
            ColorDialog clrDlg = new ColorDialog();
            if (clrDlg.ShowDialog() == DialogResult.OK)
            {
                //Save color as foregorumd color,
                //and fill text box with this color
                startColor = clrDlg.Color;
                 textBox1.BackColor = startColor;
            }
        }
 
        private void EndClrBtn_Click(object sender, System.EventArgs e)
        {
            //Use ColorDialog to select a color
            ColorDialog clrDlg = new ColorDialog();
            if (clrDlg.ShowDialog() == DialogResult.OK)
            {
                //Save color as background color,
                //and fill text box with this color
                endColor = clrDlg.Color;
                 textBox2.BackColor = endColor;
            }
        }
 
The last step is to write code for the Apply Setting button. This button reads various settings, including the selected gradient mode in the combo box, the starting and ending colors, another rectangle, and gamma correction. As Listing 4.13 shows, the code creates a linear gradient brush using a rectangle, two colors and the gradient mode selection. After creating the brush, it calls the FillRectangle method.

LISTING 4.13: The Apply Settings button click event handler

 
       private void ApplyBtn_Click(object sender, System.EventArgs e)
        {
            Graphics g = this.CreateGraphics();
            g.Clear(this.BackColor);

 
            //Read current style from combo box
            string str = comboBox1.Text;

 
            //find out the mode and set is as the current mode
            switch (str)
            {
                case "BackwardDiagonal":
                    mode = LinearGradientMode.BackwardDiagonal;
                    break;
                case "ForwardDiagonal":
                    mode = LinearGradientMode.ForwardDiagonal;
                    break;
                case "Horizontal":
                    mode = LinearGradientMode.Horizontal;
                    break;
                case "Vertical":
                    mode = LinearGradientMode.Vertical;
                    break;
                default:
                    break;
            }
 
            //Create rectangle
            Rectangle rect = new Rectangle(70, 200, 200, 220);
 
            //Create linear gradient brush and mode
            if (checkBox1.Checked)
            {
                Rectangle rect1 = new Rectangle(20, 20, 50, 50);
                lgBrush = new LinearGradientBrush
                     (rect1, startColor, endColor, mode);
            }
            else
            {
                lgBrush = new LinearGradientBrush
                    (rect, startColor, endColor, mode);
            }
 
            //Gamma correction check box is checked
 
            if (checkBox1.Checked)
            {
                 lgBrush.GammaCorrection = true;
            }
 
            //Fill Rectangle
             g.FillRectangle(lgBrush, rect);
 
            //Dispose of objects
            if (lgBrush != null)
                 lgBrush.Dispose();
            g.Dispose();
        }
 
When you run the application, the result looks like Figure 4.15.
 
Figure 4.15.jpg
 
FIGURE 4.15: The default linear gradient brush output
 
To generate a different output, let's change the linear gradient mode to Vertical. We'll also change the colors, with the results shown in Figure 4.16.
 
Let's' change the colors and gradient mode again, this time selecting the Other Rectangle check box. The sets a range of the gradient. If the output is out of range, the gradient repeats itself. The new output looks like Figure 4.17.
 
Conclusion
 
Hope the article would have helped you in understanding Gradient Brushes in GDI+. Read other articles on GDI+ on the website.
 
bookGDI.jpg
 
This book teaches .NET developers how to work with GDI+ as they develop applications that include graphics, or that interact with monitors or printers. It begins by explaining the difference between GDI and GDI+, and covering the basic concepts of graphics programming in Windows.

Up Next
    Ebook Download
    View all
    Learn
    View all