Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

Drawing Shapes Via GDI+ Brushes and Pens

1. Introduction to Dotnet GDI+

In this article we will have a look at how we perform drawing operation using the GDI+ Pen and Brush functions available with Dot Net. GDI stands for ‘Graphical Device Interface’ and using that we can create rich drawing applications, show useful information on the form as a drawing. Say, for example, one can show a pie chart of sales on past 5 years.

In this example, we will explore about the GDI+ Pen and Brushes and use them to draw some shapes in the window’s form.

2. About GDI+ Pen and Brush

A ‘Pen’ is a graphic object, which can be used to perform line drawing. GDI Pen has the properties like the color of the Pen and thickness of the pen. A Brush is also a graphic object, which we can use to paint a region. Suppose if we want to fill the area of a closed shape, we can use the Brush. One can think about Painting a door, a wooden plate, etc. In this example, we will explore how to use the ‘Pen’ and ‘Brush’. In the brush part, we will look at ‘Plain Solid Brush’, ‘Gradient Brush’ and ‘Hatch brush’.

3. About This ‘GDI+ Pen & Brush’ Example

Below is the Screen shot of this example:

DotNet GDI Plus Pen and Brush Example

Dot Net GDI Plus Pen and Brush Example

The Black screen is the Panel control and we use that here as a drawing canvas. When the user does not enable the Fill Brush whatever they draw is drawn using only the Pen. That means we see the drawing outline only that is Rectangle outline in our example. The user can switch between Solid Brush and Advanced brush using the Advanced Brush checkbox. When user enables this checkbox , they can see the advanced brush options that toggles between Hatch and Gradient using the Toggle switch. In above picture we marked it as 7.

4. Drawing Rectangle Using GDI+ Pen

To draw a rectangle in GDI+ we need its size and position. So, in the first part of the development, we place the controls to collect the Rectangle’s position and the size (Section 1 and 2 in the screenshot above). Then the rectangle is drawn in the Panel named as DrawingCanvas.

4.1 Include System.Drawing Namespace

First, we place the required namespace in the using directive to perform the 2D drawing. Note, our example requires this when we want to use the rich functionalities of the GDI+.

4.2 Construct Rectangle Object

The C# Rectangle instance can hold rectangle’s size and its position. We can use this to draw a rectangle using GDI+ APIs. We construct this rectangle using the user-supplied values.

4.3 Graphics Object & Pen Color

The black screen we see in the Sample application screenshot is a Panel Control. The CreateGraphics()  method will return the Graphics object. We can use this method on any window objects like Panel, Form or even controls like text box, list box, etc. In our case, we asked the Panel Control to retrieve the Graphics object from it. And we store this object in a variable grp of type Graphics. Once the object is ready, we construct a Pen with a color of Goldenrod, which is a preset color. You can see all the present color by Typing ‘ Color.’ in the Visual Studio IDE. Below is the code:

4.4 Clear Graphics & Draw Rectangle

Before drawing (Note we write all these codes in the Draw Button click handler), we clear existing drawing by calling the Clear() method of the Graphics object. Then the Rectangle is drawn with the user filled Rectangle dimensions.

Test Run 1: The Video Explains how the sample looks when user feeds values for the Rectangle. You can learn how Position and Size of Rectangle object helps in drawing a rectangle.


Video 1: Explains how Rectangle is Drawn


5. GDI+ Pen Color & Thickness

Using the GDI+ Pen object, we can define the color of the drawing line and its thickness. In our example, controls marked by the number 3 are used to create a pen. In the previous section we created a pen just by specifying the color. This line of code is expanded to use the user selection on the form. In this section, we will create a Pen object with a color and thickness.

5.1 Declare Variable For Pen Thickness & Color

First, we declare two variables. We assign the variable pencolor with a Color based on the Pen Color radio selection. The thickness variable holds the pen thickness. It holds either 1,3 or 5.

5.2 Assign ‘pencolor’ Variable

The user selects the Pen Color using the radio buttons. Based on the user selection, we fill assign the pencolor variable with a Color object. The code is below:

5.3 Assign ‘thickness’ Variable

The thickness variable also filled by the user selected line thickness combo box option. The pen thickness in our example has three standard thicknesses, but you can specify any float value to create a pen thickness. Below is the code that stored the pen thickness:

5.4 Construct Pen Object With Color & Thickness

Now we have pen color and thickness. Now it is time to create the GDI+ Pen object. We pass the Color and thickness to the Pen object constructor to get the Pen object. Note we already saw how to draw a rectangle and now we supply the Pen which we created based on the user preference.

Below are some Pens and look at the Lines that forms the Rectangle:

Pen Color and Thickness

Pen Color and Thickness


Video 2: Creating a Pen


6. GDI+ Brushes – Solid, Gradient & Pattern

In this section, we will explore different Brushes. Imagine a brush that we used to paint the walls of the house. We can also use the GDI+ brushes like this. We draw something using the pens that defines outer lines and then paint the enclosed region formed by the pens using brush. But we are not restricted like brush can be used only with pens. The types of brush that we are going to see here are:

  1. Simple Solid Brush
  2. Gradient Brush
  3. Patterned Brush

The Simple Solid Brush fills the color in plain solid color. Gradient Brush fills color between two colors, applying the linear transformation from one color to another color. Hatch Brushes fill the region with a given pattern. The picture here shows all these types of brushes in effect:

"Some

6.1 Enable Brush Controls

Below is the CheckedChanged event handler for the checkbox marked as four in the first picture of the article. In this handler, we enable or disable the entire GroupBox that belongs to brushes.

6.2 Hide Advanced Brush On Form Load

During the Form load, by default we will display only the Solid brush option. The user should check the Advanced Brush check box to enable the Gradient/Hatch Brush options. This code is below:

6.3 Flip Between Solid & Advanced Brush

We hide the Solid Brush when advanced brush is visible. The same way we hide the advanced brush controls when solid brush is visible.  We do this through CheckedChanged event handler of the Advanced Brush check box. Below is the code:

6.4 Flip Between Gradient & Hatch Brush

In the Example application screenshot, the control item marked as 7 is a Label Control. We use this label control as the toggle button which alternate between Gradient and Hatch. When the control label shows as Gradient the user will see controls relevant to Gradient Brush and the same hold true for the Hatch brush as well. We specify different captions for the color-based radio buttons based on the current brush mode (Gradient or Hatch). The controls specific to the hatch brush will be shown/hidden based on the current brush mode. We do this kind of work in the click event handler for the Label control:

6.5 Get Solid Brush Color From User

Below is the function GetSolidBrushColor_FromUI which gets the color for the solid brush. This function reads the user picked radio button for the solid brush color and assign that to the out parameter passed in as Color argument. Note, the out parameter assures the caller that the function will assign a value in the color argument and the caller no need to set the default value. The function is below:

6.6 Gradient & Pattern Brush Color

Look at the sample application screenshot marked as 6 and here the GroupBox names ‘From’ and ‘To’ will be changed as ‘ForeColor’ and ‘BackColor’ when the Brush Mode changes from Gradient to Hatch. The function shown below will return the color values from the same Radio buttons that comes under these two set of radio groups which changes their name based on the brush mode:

6.7 Diminish Rectangle Dimension For Filling

The Inflate_Rect function below will reduce the rectangular size based on the current pen thickness. Note that the function takes the argument as the reference type. Hence, the caller can expect the changes in reference argument with reduced size which will not overlap with pen drawing.

6.8 Fill Rectangle Using GDI+ Solid Brush

Till now we looked at some helper functions which we wrote for this example. Now we will look at the Solid Brush and its filling techniques. In the OnPaint handler, after drawing the rectangle with the required Pen attributes, we fill the rectangle with the user selection of brush. Note that before making the fill operation using the brush, the rectangle drawn using the Pen is inflated. We can create a Solid Brush by specifying the color. The Graphics object supports a lot of drawing functions with a fill, say for example something like FillRectangle, FillEllipse, etc.

In the below code we make sure the user does not select the advanced brush option and then create a Solid Brush by specifying the solid fill color in the SolidBrush constructor. After creating the Solid Brush, we can use it to fill our rectangle using the Graphics object. In our case we used the solid brush with the FillRectangle function. Below is the code that creates and uses the Solid Brush:

6.9 Fill Rectangle Using GDI+ Gradient Brush

Based on the Toggle Label, we create the Gradient Brush. To create Gradient Brush, we need two colors as the gradient interpolates two colors linearly. Look at the past picture for the Gradient Brush and in that the color interpolation is spread between blue and green horizontally. In our example, we get both the colors needed for the gradient effect by making a call to our helper function Get_Col1_Col2. Then we pass the from_color and to_color to the LinearGradientBrush constructor to create the Gradient Brush object. Once we have Gradient Brush in hand, we make a call to the function FillRectangle to get the Gradient effect. The code for this is below:

In the above code, we asked the gradient to be applied horizontally by specifying the LinearGradientMode.Horizontal. The below picture shows supported Gradient Modes:

Gradient Modes

Gradient Modes

6.10 Fill Rectangle Using GDI+ Hatch Brush

In the else part of the Gradient Brush section, we create the Pattern Brush to fill the rectangle. Note, Pattern Brush is an alternate name for Hatch Brush. To see the pattern, we should specify the BackColor and ForeColor when creating the Pattern Brush. After having these colors (Note we used same function call Get_Col1_Col2), the User-Selected hatch pattern is stored in the HatchStyle object. Refer MSDN to know other hatch patterns as there are much more patterns available. We pass all this information to HatchBrush constructor to create the object Hatch_brush. Then, as usual, we pass this hatch brush to the FillRectangle function of the Graphics object. The code is below which constructs the Pattern Brush and uses that to fill the rectangle:

The below video shows how our example uses the GDI+ Brushes.


Video 3: Creating and using Brushes


Source Code: Download GDI+ Pen and Brush Example from Google Drive

Categories: C#

Tags: , , , , ,

Do you like this Example? Share your thoughts!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.