Home

Introduction to Brushes

 

Fundamentals of Brushes

 

Introduction

In the previous lesson, we drew two types of figures: line-based and closed shapes. These figures required a pen to show their shape. The particularity with closed shapes is that they can be filled, with a color, a picture, or a pattern.

A brush is an object that holds a color, a picture, or a drawing pattern and that is used to fill the interior of a closed shape. This definition also means that there are various types of brushes with different goals. To meet these goals, the .NET Framework provides support for brushes in various namespaces with different classes. The parent of all brushes is the Brush class defined in the System.Drawing namespace.

 

Using a Brush

Because the main job of a brush is to fill a closed shape, the Graphics class provides a method that corresponds to each of the closed shapes we reviewed to draw in the previous lesson in order to fill it. The methods are:

  • FillRectangle: Used to fill the interior of a rectangle or a square
  • FillRectangle: Used to fill the interior of a series of rectangles
  • FillEllipse: Used to fill the interior of an ellipse or a circle
  • FillPolygon: Used to fill the interior of a polygon
  • FillClosedCurve: Used to fill the interior of a closed curve
  • FillPie: Used to fill the interior of a pie
  • FillPath: Used to fill the interior of a graphic path

To fill out a shape, call one of these methods, pass it a brush value, followed by the location and dimensions of the shape. For example, if you want to draw a rectangle and fill it with a brush, you would use code similar to:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : Form
{
    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        Paint += new PaintEventHandler(Exercise_Paint);
    }

    private void Exercise_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.FillRectangle(SomeBrush, 20, 20, 200, 160);
    }
}

public class Program
{
    public static int Main()
    {
        Application.Run(new Exercise());

        return 0;
    }
}

Over all, there are four types of brushes.

Solid Brushes

 

Simple Colored Brushes

Like a pen, the primary characteristic of a brush is its color. To help you create a simple brush, the System.Drawing namespace provides the static sealed Brushes class. The only feature this class provides is the ability to specify a color to use on a brush. As a static class, you never have to instantiate it.

To create a simple brush whose only information is provided by its color, call the Brushes class and access a color by qualifying it with the name of the class. Each color is provided by its name as a property. Here is an example of using the class:

private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    Point[] pt = { new Point(10,  22), new Point(188, 246),
                          new Point(280, 192), new Point(250,  48) };

    e.Graphics.FillClosedCurve(Brushes.BlanchedAlmond, pt);
    e.Graphics.DrawClosedCurve(Pens.Blue, pt);
}

This would produce:

Brush

 

Practical LearningPractical Learning: Drawing a Circle

  1. Start a new Windows Application named RotatingCircles1
  2. Double-click middle of the form and change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace RotatingCircles1
    {
        public partial class Form1 : Form
        {
            Graphics graphDrawingArea;
            Bitmap bmpDrawingArea;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                bmpDrawingArea = new Bitmap(Width, Height);
                graphDrawingArea = Graphics.FromImage(bmpDrawingArea);
            }
        }
    }
  3. From the Components section of the Toolbox, click Timer and click the form
  4. In the Properties window, change the following values:
    Enabled: True
    Interval: 20
  5. Under the form, double-click the timer1 object and make the following changes:
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace RotatingCircles1
    {
        public partial class Form1 : Form
        {
            Graphics graphDrawingArea;
            Bitmap bmpDrawingArea;
            static int mainRadius = 10;
            static int smallRadius = 5;
            static bool isMax;
            static bool smallRadiusMax;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                bmpDrawingArea = new Bitmap(Width, Height);
                graphDrawingArea = Graphics.FromImage(bmpDrawingArea);
            }
    
            void DrawCentralCircle(int CenterX, int CenterY, int Radius)
            {
                int start = CenterX - Radius;
                int end = CenterY - Radius;
                int diam = Radius * 2;
    
                graphDrawingArea.DrawEllipse(new Pen(Color.Blue),
                              start, end, diam, diam);
            }
    
            void DrawCornerCircle(int CenterX, int CenterY, int Radius)
            {
                int start = CenterX - Radius;
                int end = CenterY - Radius;
                int diam = Radius * 2;
    
                graphDrawingArea.DrawEllipse(new Pen(Color.Red),
                              start, end, diam, diam);
            }
    
            private void timer1_Tick(object sender, EventArgs e)
            {
                Graphics graph = Graphics.FromHwnd(this.Handle);
    
                int centerX = ClientRectangle.Width / 2;
                int centerY = ClientRectangle.Height / 2;
    
                if (isMax == true)
                    mainRadius--;
                else
                    mainRadius++;
    
                if (mainRadius > (ClientRectangle.Height / 2))
                    isMax = true;
                if (mainRadius < 10)
                    isMax = false;
    
                if (smallRadiusMax == true)
                    smallRadius--;
                else
                    smallRadius++;
    
                if (smallRadius > 240)
                    smallRadiusMax = true;
                if (smallRadius < 5)
                    smallRadiusMax = false;
    
                graphDrawingArea.FillRectangle(Brushes.Black, 
    						0, 0, Width, Height);
    
                // Central
                DrawCentralCircle(centerX, centerY, mainRadius);
                // Top-Left
                DrawCornerCircle(centerX / 2, centerY / 2, smallRadius);
                // Top-Right
                DrawCornerCircle(centerX + (centerX / 2), 
    				centerY / 2, smallRadius);
                // Bottom-Left
                DrawCornerCircle(centerX / 2, 
    		centerY + (centerY / 2), smallRadius);
                // BottomRight
                DrawCornerCircle(centerX + (centerX / 2),
                         centerY + (centerY / 2), smallRadius);
    
                graph.DrawImage(bmpDrawingArea, 0, 0);
            }
        }
    }
  6. Execute the application to see the result
     
    Rotating Circles
  7. Close the form

Creating a Solid Brush

The simplest type of brush is referred to as solid. This type of brush is simply equipped with a color and it is used to fill a shape with it. To get a solid brush, you use the SolidBrush class defined in the System.Drawing namespace. It has only one constructor declared with the following syntax:

public SolidBrush(Color color);

The color passed as argument must be a valid definition of a Color. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        SolidBrush brushBlue = new SolidBrush(Color.Blue);

        e.Graphics.FillRectangle(brushBlue, 20, 20, 200, 160);
}

This would produce:

Brush

If you plan to use different colors to fill different shapes, you don't have to create a new brush for each shape. At any time, before re-using the same brush previously defined, you can simply change its Color. For this reason, the SolidBrush class is equipped with the Color property. Here is an example of using it:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        SolidBrush colorizer = new SolidBrush(Color.Lime);
        e.Graphics.FillRectangle(colorizer, 10, 10, 120, 120);

        colorizer.Color = Color.Salmon;
        e.Graphics.FillRectangle(colorizer, 140, 10, 120, 120);

        colorizer.Color = Color.Aqua;
        e.Graphics.FillRectangle(colorizer, 10, 140, 120, 120);

        colorizer.Color = Color.Navy;
        e.Graphics.FillRectangle(colorizer, 140, 140, 120, 120);
}

This would produce:

Solid Brushes

Like most objects used in graphics programming, a brush consumes the computer resources. Therefore, after using it, you can free the resources it was using by calling the Dispose() method. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        SolidBrush colorizer = new SolidBrush(Color.Lime);
        e.Graphics.FillRectangle(colorizer, 10, 10, 120, 120);

        colorizer.Color = Color.Salmon;
        e.Graphics.FillRectangle(colorizer, 140, 10, 120, 120);

        colorizer.Color = Color.Aqua;
        e.Graphics.FillRectangle(colorizer, 10, 140, 120, 120);

        colorizer.Color = Color.Navy;
        e.Graphics.FillRectangle(colorizer, 140, 140, 120, 120);

    colorizer.Dispose();
}

Practical LearningPractical Learning: Using a Solid Brush

  1. Start a new Windows Forms Application named WeeklySales2
  2. Design the form as follows:
     
    Company Weekly Sales
    Control Name Text Other Properties
    Label Label   Monday  
    Label Label   Tuesday  
    Label Label   Wednesday  
    Label Label   Thursday  
    Label Label   Friday  
    TextBox TextBox txtMonday 12000 TextAlign: Right
    TextBox TextBox txtTuesday 11000 TextAlign: Right
    TextBox TextBox txtWednesday 8500 TextAlign: Right
    TextBox TextBox txtThursday 16800 TextAlign: Right
    TextBox TextBox txtFriday 17500 TextAlign: Right
    Button Button Generate btnGenerate  
  3. Double-click an unoccupied area of the form and change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace WeeklySales2
    {
        public partial class Form1 : Form
        {
            Graphics graphDrawingArea;
            Bitmap bmpDrawingArea;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                bmpDrawingArea = new Bitmap(Width, Height);
                graphDrawingArea = Graphics.FromImage(bmpDrawingArea);
            }
        }
    }
  4. Return to the form and click an empty area on it. In the Properties window, click the Events button Events
  5. Double-click the Paint field and implement its event as follows:
     
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
                e.Graphics.DrawImage(bmpDrawingArea, 0, 0);
    }
  6. Return to the form and double-click the Generate button
  7. Implement its Click event as follows:
     
    private void btnGenerate_Click(object sender, EventArgs e)
    {
                int monday = 0;
                int tuesday = 0;
                int wednesday = 0;
                int thursday = 0;
                int friday = 0;
    
                try
                {
                    monday = int.Parse(txtMonday.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value");
                }
    
                try
                {
                    tuesday = int.Parse(txtTuesday.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value");
                }
    
                try
                {
                    wednesday = int.Parse(txtWednesday.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value");
                }
    
                try
                {
                    thursday = int.Parse(txtThursday.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value");
                }
    
                try
                {
                    friday = int.Parse(txtFriday.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value");
                }
    
                graphDrawingArea.Clear(this.BackColor);
    
                graphDrawingArea.FillRectangle(new SolidBrush(Color.Red),
                        this.txtMonday.Left + 5,
                        280 - monday, 40, monday);
                graphDrawingArea.DrawRectangle(new Pen(Color.Black),
                        this.txtMonday.Left + 5,
                            280 - monday, 40, monday);
                graphDrawingArea.FillRectangle(new SolidBrush(Color.Blue),
                        this.txtTuesday.Left + 5,
                        280 - tuesday, 40, tuesday);
                graphDrawingArea.DrawRectangle(new Pen(Color.Black),
                        this.txtTuesday.Left + 5,
                            280 - tuesday, 40, tuesday);
                graphDrawingArea.FillRectangle(new SolidBrush(Color.Fuchsia),
                        this.txtWednesday.Left + 5,
                        280 - wednesday, 40, wednesday);
                graphDrawingArea.DrawRectangle(new Pen(Color.Black),
                        this.txtWednesday.Left + 5,
                        280 - wednesday, 40, wednesday);
                graphDrawingArea.FillRectangle(new SolidBrush(Color.Brown),
                        this.txtThursday.Left + 5,
                        280 - thursday, 40, thursday);
                graphDrawingArea.DrawRectangle(new Pen(Color.Black),
                        this.txtThursday.Left + 5,
                        280 - thursday, 40, thursday);
                graphDrawingArea.FillRectangle(new SolidBrush(Color.Turquoise),
                        this.txtFriday.Left + 5,
                        280 - friday, 40, friday);
                graphDrawingArea.DrawRectangle(new Pen(Color.Black),
                        this.txtFriday.Left + 5,
                            280 - friday, 40, friday);
    
                graphDrawingArea.DrawRectangle(new Pen(Color.Black),
                        10, 280, Width - 30, 1);
                Invalidate();
    }
  8. Execute the application and test the form
     
     Weekly Sales
  9. After using it, close the form

Hatch Brushes

 

Introduction

A hatch brush relies on a drawn or designed pattern to set its filling type. To support hatch brushes, the .NET Framework provides the patterns you can use as part of the brush. These pre-designed patterns are referred to as hatch styles. This means that when you use a hatch brush, you must specify the type of pattern you want to use, through one of the available hatch styles. To make the filled area more interesting, you also specify the color to use when drawing the pattern.

To get a hatch brush, you use the HatchBrush class. One of its constructors has the following syntaxes:

public HatchBrush(HatchStyle style, Color foreColor);

The Style of a Hatch Brush

The foreColor argument is the color that will be used to draw the pattern. The style argument is the hatch style you want to apply. Some of the available styles are:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

public class Exercise : Form
{
    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        Paint += new PaintEventHandler(Exercise_Paint);
    }

    private void Exercise_Paint(object sender, PaintEventArgs e)
    {
        HatchBrush brushBackDiag =
    new HatchBrush(HatchStyle.BackwardDiagonal,
             Color.FromArgb(0, 0, 255));
        HatchBrush brushCross =
        new HatchBrush(HatchStyle.Cross,
                 Color.FromArgb(200, 0, 0));
        HatchBrush brushDarkDown =
        new HatchBrush(HatchStyle.DarkDownwardDiagonal,
                 Color.Salmon);
        HatchBrush brushDarkHorz =
        new HatchBrush(HatchStyle.DarkHorizontal,
                 Color.Navy);
        HatchBrush brushDarkUpDiag =
        new HatchBrush(HatchStyle.DarkUpwardDiagonal,
                 Color.Pink);
        HatchBrush brushVertical =
        new HatchBrush(HatchStyle.DarkVertical,
                 Color.FromArgb(255, 0, 255));
        HatchBrush brushDashDnDiag =
        new HatchBrush(HatchStyle.DashedDownwardDiagonal,
                 Color.FromArgb(255, 128, 0));
        HatchBrush brushDashHorz =
        new HatchBrush(HatchStyle.DashedHorizontal,
                 Color.FromArgb(0, 128, 192));
        HatchBrush brushDashUpDiag =
        new HatchBrush(HatchStyle.DashedUpwardDiagonal,
                 Color.Green);
        HatchBrush brushDashVert =
        new HatchBrush(HatchStyle.DashedVertical,
                 Color.Firebrick);
        HatchBrush brushDiagBrisk =
        new HatchBrush(HatchStyle.DiagonalBrick,
                 Color.Fuchsia);
        HatchBrush brushDiagCross =
        new HatchBrush(HatchStyle.DiagonalCross,
                 Color.Moccasin);
        HatchBrush brushDivot =
        new HatchBrush(HatchStyle.Divot,
                 Color.Goldenrod);
        HatchBrush brushDotDiamond =
        new HatchBrush(HatchStyle.DottedDiamond,
                 Color.Gainsboro);
        HatchBrush brushDottedGrid =
        new HatchBrush(HatchStyle.DottedGrid,
                 Color.Khaki);
        HatchBrush brushForDiag =
        new HatchBrush(HatchStyle.ForwardDiagonal,
                 Color.Maroon);
        HatchBrush brushHorz =
        new HatchBrush(HatchStyle.Horizontal,
                 Color.Red);
        HatchBrush brushHorzBrick =
        new HatchBrush(HatchStyle.HorizontalBrick,
                 Color.SaddleBrown);
        HatchBrush brushLgChkBoard =
        new HatchBrush(HatchStyle.LargeCheckerBoard,
                 Color.RoyalBlue);
        HatchBrush brushLgConfetti =
        new HatchBrush(HatchStyle.LargeConfetti,
                 Color.MistyRose);
        HatchBrush brushLgGrid =
        new HatchBrush(HatchStyle.LargeGrid,
                 Color.Purple);
        HatchBrush brushLtDnDiag =
        new HatchBrush(HatchStyle.LightDownwardDiagonal,
                 Color.DarkCyan);
        HatchBrush brushLtHorz =
        new HatchBrush(HatchStyle.LightHorizontal,
                 Color.PowderBlue);
        HatchBrush brushUpDiag =
        new HatchBrush(HatchStyle.LightUpwardDiagonal,
                 Color.SeaGreen);
        HatchBrush brushLtVert =
        new HatchBrush(HatchStyle.LightVertical,
                 Color.Olive);

        e.Graphics.FillRectangle(brushBackDiag,
                       20, 20, 80, 60);
        e.Graphics.FillRectangle(brushCross,
                       120, 20, 80, 60);
        e.Graphics.FillRectangle(brushDarkDown,
                       220, 20, 80, 60);
        e.Graphics.FillRectangle(brushDarkHorz,
                       320, 20, 80, 60);
        e.Graphics.FillRectangle(brushDarkUpDiag,
                       420, 20, 80, 60);

        e.Graphics.FillRectangle(brushVertical,
                           20, 100, 80, 60);
        e.Graphics.FillRectangle(brushDashDnDiag,
                       120, 100, 80, 60);
        e.Graphics.FillRectangle(brushDashHorz,
                       220, 100, 80, 60);
        e.Graphics.FillRectangle(brushDashUpDiag,
                       320, 100, 80, 60);
        e.Graphics.FillRectangle(brushDashVert,
                       420, 100, 80, 60);

        e.Graphics.FillRectangle(brushDashVert,
                       20, 180, 80, 60);
        e.Graphics.FillRectangle(brushDiagBrisk,
                       120, 180, 80, 60);
        e.Graphics.FillRectangle(brushDiagCross,
                       220, 180, 80, 60);
        e.Graphics.FillRectangle(brushDivot,
                       320, 180, 80, 60);
        e.Graphics.FillRectangle(brushDotDiamond,
                       420, 180, 80, 60);

        e.Graphics.FillRectangle(brushDottedGrid,
                       20, 260, 80, 60);
        e.Graphics.FillRectangle(brushForDiag,
                       120, 260, 80, 60);
        e.Graphics.FillRectangle(brushHorz,
                           220, 260, 80, 60);
        e.Graphics.FillRectangle(brushHorzBrick,
                       320, 260, 80, 60);
        e.Graphics.FillRectangle(brushLgChkBoard,
                       420, 260, 80, 60);

        e.Graphics.FillRectangle(brushLgGrid,
                       20, 340, 80, 60);
        e.Graphics.FillRectangle(brushLtDnDiag,
                       120, 340, 80, 60);
        e.Graphics.FillRectangle(brushLtHorz,
                       220, 340, 80, 60);
        e.Graphics.FillRectangle(brushUpDiag,
                       320, 340, 80, 60);
        e.Graphics.FillRectangle(brushLtVert,
                       420, 340, 80, 60);
    }
}

public class Program
{
    public static int Main()
    {
        Application.Run(new Exercise());

        return 0;
    }
}

This would produce:

Hatch Brushes

Practical LearningPractical Learning: Using a Hatch Brush

  1. Start a new Windows Forms Application named YearlySales2
  2. Design the form as follows:
     
    Company Yearly Sales
     
    Control Name Text
    GroupBox GroupBox   Current Year's Sales
    Label Label   1st Qtr
    Label Label   2nd Qtr
    Label Label   3rd Qtr
    Label Label   4th Qtr
    TextBox TextBox txtCurrentQtr1 0
    TextBox TextBox txtCurrentQtr2 0
    TextBox TextBox txtCurrentQtr3 0
    TextBox TextBox txtCurrentQtr4 0
    Button Button Close btnClose
    GroupBox GroupBox   Previous Year's Sales
    Label Label   1st Qtr
    Label Label   2nd Qtr
    Label Label   3rd Qtr
    Label Label   4th Qtr
    TextBox TextBox txtPreviousQtr1 0
    TextBox TextBox txtPreviousQtr2 0
    TextBox TextBox txtPreviousQtr3 0
    TextBox TextBox txtPreviousQtr4 0
    Button Button Generate btnGenerate
    Label Label   _________ Legend _________
    Label Label   This Year's Sales
    Label Label   Last Year's Sales
  3. Double-click an unoccupied area of the form and change the file  as follows:
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Drawing.Drawing2D;
    
    namespace YearlySales2
    {
        public partial class Form1 : Form
        {
            Graphics graphDrawingArea;
            Bitmap bmpDrawingArea;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                bmpDrawingArea = new Bitmap(Width, Height);
                graphDrawingArea = Graphics.FromImage(bmpDrawingArea);
            }
        }
    }
  4. Return to the form and click an empty area on it. In the Properties window, click the Events button Events
  5. Double-click the Paint field and implement its event as follows:
     
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
                e.Graphics.DrawImage(bmpDrawingArea, 0, 0);
    }
  6. Return to the form and double-click the Generate button
  7. Implement the event as follows:
     
    private void btnGenerate_Click(object sender, EventArgs e)
    {
                // Retrieve the values of the current year's sales
                int curQtr1 = 0;
                int curQtr2 = 0;
                int curQtr3 = 0;
                int curQtr4 = 0;
    
                try
                {
                    curQtr1 = int.Parse(txtCurrentQtr1.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                try
                {
                    curQtr2 = int.Parse(txtCurrentQtr2.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                try
                {
                    curQtr3 = int.Parse(txtCurrentQtr3.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                try
                {
                    curQtr4 = int.Parse(txtCurrentQtr4.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                // Create an array of Rectangle objects for the current year
                Rectangle[] rectCurrentYear =
                {
                    new Rectangle(this.txtCurrentQtr1.Left+20,
    			                  380-curQtr1, 40, curQtr1),
                    new Rectangle(this.txtCurrentQtr2.Left+20,
    			                   380-curQtr2, 40, curQtr2),
    		        new Rectangle(this.txtCurrentQtr3.Left+20,
    			                  380-curQtr3, 40, curQtr3),
    		        new Rectangle(this.txtCurrentQtr4.Left+20,
    			                  380-curQtr4, 40, curQtr4)
                };
    
                // Retrieve the values of last year's sales
                int prvQtr1 = 0;
                int prvQtr2 = 0;
                int prvQtr3 = 0;
                int prvQtr4 = 0;
    
                try
                {
                    prvQtr1 = int.Parse(txtPreviousQtr1.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                try
                {
                    prvQtr2 = int.Parse(txtPreviousQtr2.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                try
                {
                    prvQtr3 = int.Parse(txtPreviousQtr3.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                try
                {
                    prvQtr4 = int.Parse(txtPreviousQtr4.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Value");
                }
    
                // Create an array of Rectangle objects for the previous year
                Rectangle[] rectPreviousYear =
                {
                    new Rectangle(this.txtPreviousQtr1.Left+30,
    			                  380-prvQtr1, 40, prvQtr1),
     		        new Rectangle(this.txtPreviousQtr2.Left+30,
    			                  380-prvQtr2, 40, prvQtr2),
    	            new Rectangle(this.txtPreviousQtr3.Left+30,
    			                  380-prvQtr3, 40, prvQtr3),
    		        new Rectangle(this.txtPreviousQtr4.Left+30,
    			                  380-prvQtr4, 40, prvQtr4)
                };
    
                // In case the user has changed 
    	    //  the values, erase the previous chart
                graphDrawingArea.Clear(this.BackColor);
    
                HatchBrush brushDiagCross =
                 new HatchBrush(HatchStyle.DiagonalCross,
                          Color.White, Color.Blue);
                HatchBrush brushDotDiamond =
                 new HatchBrush(HatchStyle.DottedDiamond,
                          Color.Fuchsia, Color.Brown);
    
                // Draw the chart for the previous year first to send it back
                graphDrawingArea.FillRectangles(brushDiagCross,
                                 rectPreviousYear);
                graphDrawingArea.DrawRectangles(new Pen(Color.Blue),
                                 rectPreviousYear);
                // Draw the chart for the current year in front
                graphDrawingArea.FillRectangles(brushDotDiamond,
                                 rectCurrentYear);
                graphDrawingArea.DrawRectangles(new Pen(Color.Red),
                                 rectCurrentYear);
    
                // Draw the small rectangles of the legend
                graphDrawingArea.FillRectangle(brushDotDiamond,
                                this.lblCurYear.Left - 30,
                                this.lblCurYear.Top, 20, 14);
                graphDrawingArea.DrawRectangle(new Pen(Color.Red),
                                this.lblCurYear.Left - 30,
                                this.lblCurYear.Top, 20, 14);
                graphDrawingArea.FillRectangle(brushDiagCross,
                                this.lblLastYear.Left - 30,
                                this.lblLastYear.Top, 20, 14);
                graphDrawingArea.DrawRectangle(new Pen(Color.Blue),
                                this.lblLastYear.Left - 30,
                                this.lblLastYear.Top, 20, 14);
    
                graphDrawingArea.DrawRectangle(new Pen(Color.Black),
                                25, 380, Width - 220, 1);
                Invalidate();
    }
  8. Return to the form. Double-click the Close button and implement its Click event as follows:
     
    private void btnClose_Click(object sender, EventArgs e)
    {
                Close();
    }
  9. Execute the application and test the form
     
     Yearly Sales
  10. After using it, close the form

The Background Color of a Hatch Brush

If you use the above constructor to fill out a shape, the selected pattern would be drawn on top of a black color used as the background. If you want to use a different background, use the following constructor to initialize the brush:

public HatchBrush(HatchStyle hatchstyle, Color foreColor, Color backColor);

The backColor argument passed as a Color value will be used as the background Color. Here are examples of specifying the back color:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        HatchStyle[] hsBrush =
        {
            HatchStyle.BackwardDiagonal,
            HatchStyle.Cross, HatchStyle.Divot,
            HatchStyle.DarkDownwardDiagonal,
            HatchStyle.DarkHorizontal, HatchStyle.ForwardDiagonal,
            HatchStyle.DarkUpwardDiagonal,
            HatchStyle.DarkVertical, HatchStyle.HorizontalBrick,
            HatchStyle.DashedDownwardDiagonal,
            HatchStyle.DashedHorizontal,
            HatchStyle.DashedVertical, HatchStyle.LargeCheckerBoard,
            HatchStyle.DiagonalBrick, HatchStyle.Horizontal,
            HatchStyle.DiagonalCross, HatchStyle.DottedGrid,
            HatchStyle.DottedDiamond, HatchStyle.LightUpwardDiagonal,  
            HatchStyle.LargeConfetti, HatchStyle.LargeGrid,
            HatchStyle.LightDownwardDiagonal, HatchStyle.OutlinedDiamond
            HatchStyle.LightHorizontal, HatchStyle.LightVertical
        };

        Color[] ForeColors =
        {
            Color.FromArgb(0, 0, 255), Color.FromArgb(200, 0, 0),
            Color.Salmon, Color.Navy, Color.Pink,
            Color.FromArgb(255, 0, 255), Color.FromArgb(255, 128, 0),
            Color.FromArgb(0, 128, 192), Color.Green,
            Color.Firebrick, Color.Fuchsia, Color.Moccasin,
            Color.Goldenrod, Color.Gainsboro, Color.Khaki,
            Color.Maroon, Color.DarkCyan, Color.Purple,
            Color.MistyRose, Color.RoyalBlue, Color.Red,
            Color.SaddleBrown, Color.Olive, Color.SeaGreen,
            Color.PowderBlue
        };

        Color[] BackColors =
        {
            Color.Azure, Color.DarkBlue, Color.AntiqueWhite,
            Color.Aqua, Color.DarkGray, Color.Aquamarine,
            Color.Azure, Color.Beige, Color.DarkGoldenrod,
            Color.Bisque, Color.DarkKhaki, Color.BlanchedAlmond,
            Color.Brown, Color.DarkCyan, Color.AliceBlue,
            Color.BurlyWood, Color.CadetBlue, Color.DarkMagenta,
            Color.Coral, Color.Chartreuse, Color.CornflowerBlue,
            Color.Cornsilk, Color.Crimson, Color.Cyan,
            Color.DarkGreen
        };

        Random rnd = new Random();

        HatchBrush brushBackDiag =
    new HatchBrush(hsBrush[rnd.Next(25)],
             ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushCross =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDarkDown =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDarkHorz =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDarkUpDiag =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushVertical =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDashDnDiag =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDashHorz =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDashUpDiag =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDashVert =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDiagBrisk =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDiagCross =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDivot =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDotDiamond =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushDottedGrid =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushForDiag =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushHorz =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushHorzBrick =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushLgChkBoard =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushLgConfetti =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushLgGrid =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushLtDnDiag =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushLtHorz =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushUpDiag =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);
        HatchBrush brushLtVert =
        new HatchBrush(hsBrush[rnd.Next(25)],
                 ForeColors[rnd.Next(25)], BackColors[rnd.Next(25)]);

        e.Graphics.FillRectangle(brushBackDiag, 20, 20, 80, 60);
        e.Graphics.FillRectangle(brushCross, 120, 20, 80, 60);
        e.Graphics.FillRectangle(brushDarkDown, 220, 20, 80, 60);
        e.Graphics.FillRectangle(brushDarkHorz, 320, 20, 80, 60);
        e.Graphics.FillRectangle(brushDarkUpDiag, 420, 20, 80, 60);

        e.Graphics.FillRectangle(brushVertical, 20, 100, 80, 60);
        e.Graphics.FillRectangle(brushDashDnDiag, 120, 100, 80, 60);
        e.Graphics.FillRectangle(brushDashHorz, 220, 100, 80, 60);
        e.Graphics.FillRectangle(brushDashUpDiag, 320, 100, 80, 60);
        e.Graphics.FillRectangle(brushDashVert, 420, 100, 80, 60);

        e.Graphics.FillRectangle(brushDashVert, 20, 180, 80, 60);
        e.Graphics.FillRectangle(brushDiagBrisk, 120, 180, 80, 60);
        e.Graphics.FillRectangle(brushDiagCross, 220, 180, 80, 60);
        e.Graphics.FillRectangle(brushDivot, 320, 180, 80, 60);
        e.Graphics.FillRectangle(brushDotDiamond, 420, 180, 80, 60);

        e.Graphics.FillRectangle(brushDottedGrid, 20, 260, 80, 60);
        e.Graphics.FillRectangle(brushForDiag, 120, 260, 80, 60);
        e.Graphics.FillRectangle(brushHorz, 220, 260, 80, 60);
        e.Graphics.FillRectangle(brushHorzBrick, 320, 260, 80, 60);
        e.Graphics.FillRectangle(brushLgChkBoard, 420, 260, 80, 60);

        e.Graphics.FillRectangle(brushLgGrid, 20, 340, 80, 60);
        e.Graphics.FillRectangle(brushLtDnDiag, 120, 340, 80, 60);
        e.Graphics.FillRectangle(brushLtHorz, 220, 340, 80, 60);
        e.Graphics.FillRectangle(brushUpDiag, 320, 340, 80, 60);
        e.Graphics.FillRectangle(brushLtVert, 420, 340, 80, 60);
}

At any time, to find out the color used to paint a pattern, you can access the brush's ForegroundColor property. To know the color used as background, you can access the brush's BackgroundColor property. To know the hatch style used on the current brush, you can access its HatchStyle property.

 
 

Previous Copyright 2008-2009, yevol.com Next