Home

GDI+: Regular Shapes

 

Rectangles and Squares

A rectangle is a geometric figure made of four sides that compose four right angles. To draw a rectangle, you can either specify the Rectangle value that encloses it, or you can define its location and its dimensions. To draw a rectangle that is enclosed in a Rectangle value, you can use the following version of the Graphics.DrawRectangle() method:

public void DrawRectangle(Pen pen, Rectangle rect);

Remember that such a rectangle object can be illustrated as follows:

After defining a Rectangle variable, you can pass it to the method. Here is an example:

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)
    {
        Pen penCurrent = new Pen(Color.Red);
        Rectangle Rect = new Rectangle(20, 20, 248, 162);

        e.Graphics.DrawRectangle(penCurrent, Rect);
    }
}

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

        return 0;
    }
}

Remember that you can also define a Pen and/or a Rectangle objects in the parentheses of the method:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        e.Graphics.DrawRectangle(new Pen(Color.Red),
                   new Rectangle(20, 20, 248, 162));
}

This would produce:

A Rectangle Drawn From a Rectangle Value

It is (very) important to remember that the third argument of the Rectangle represents its width (and not its right) value and the fourth argument represents its height (and not its bottom) value. This is a confusing fact for those who have programmed in GDI: GDI+ defines a Rectangle differently than GDI. In fact, to determine the location and dimensions of a rectangle to draw, the Graphics class provides the following versions of the DrawRectangle() method:

public 
   void DrawRectangle(Pen pen,
		      int x,
		      int y,
		      int width,
		      int height);
   void DrawRectangle(Pen pen,
		      float x,
		      float y,
		      float width,
		      float height);

This time, the rectangle is represented by its location with a point at (x, y) and its dimensions with the width and height argument. This can be illustrated in a Windows coordinate system as follows:

Rectangle

Based on this, the earlier rectangle can also be drawn with the following:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        e.Graphics.DrawRectangle(new Pen(Color.Red), 20, 20, 248, 162);
}

A square is a rectangle whose four sides are equal.

Practical LearningPractical Learning: Drawing a Rectangle

  1. Start Microsoft Visual C# and create a new Windows Application named WeeklySales1
  2. Design the form as follows:
     
    Weekly Sales
    Control Name Text
    Label Label   Monday
    Label Label   Tuesday
    Label Label   Wednesday
    Label Label   Thursday
    Label Label   Friday
    TextBox TextBox txtMonday 0
    TextBox TextBox txtTuesday 0
    TextBox TextBox txtWednesday 0
    TextBox TextBox txtThursday 0
    TextBox TextBox txtFriday 0
    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.Text;
    using System.Windows.Forms;
    
    namespace WeeklySales1
    {
        public partial class Form1 : Form
        {
            private Graphics graphDrawingArea;
            private 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)
    {
            int monday= 0,
                 tuesday   = 0,
                 wednesday = 0,
                 thursday  = 0,
                 friday    = 0;
    
            try
            {
                    monday = int.Parse(txtMonday.Text) / 100;
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid sales on Monday");
                    txtMonday.Text = "0";
            }
    
            try
            {
                    tuesday = int.Parse(txtTuesday.Text) / 100;
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid sales on Tuesday");
                    txtTuesday.Text = "0";
            }
    
            try
            {
                    wednesday = int.Parse(txtWednesday.Text) / 100;
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid sales on Wednesday");
                    txtWednesday.Text = "0";
            }
    
            try
            {
                    thursday = int.Parse(txtThursday.Text) / 100;
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid sales on Thursday");
                    txtThursday.Text = "0";
            }
    
            try
            {
                    friday = int.Parse(txtFriday.Text) / 100;
            }
            catch (FormatException)
            {
                    MessageBox.Show("Invalid sales on Friday");
                    txtFriday.Text = "0";
            }
    
            graphDrawingArea.Clear(this.BackColor);
    
            graphDrawingArea.DrawRectangle(new Pen(Color.Red),
                                this.txtMonday.Left + 10,
                                300 - monday,
                                40, monday);
            graphDrawingArea.DrawRectangle(new Pen(Color.Blue),
                                this.txtTuesday.Left + 10,
                                300 - tuesday,
                                40, tuesday);
            graphDrawingArea.DrawRectangle(new Pen(Color.Fuchsia),
                                this.txtWednesday.Left + 5,
                                300 - wednesday,
                                40, wednesday);
            graphDrawingArea.DrawRectangle(new Pen(Color.Brown),
                                this.txtThursday.Left + 5,
                                300 - thursday,
                                40, thursday);
            graphDrawingArea.DrawRectangle(new Pen(Color.Turquoise),
                                this.txtFriday.Left + 5,
                                300 - friday, 40, friday);
    
            graphDrawingArea.DrawRectangle(new Pen(Color.Black),
                                10, 300, Width - 30, 1);
            Invalidate();
    }
  8. Execute the application and test the form
     
     
  9. After using it, close the form

A Series of Rectangles

The DrawRectangle() method is used to draw one rectangle. If you plan to draw many rectangles, you can proceed in one step by using the Graphics.DrawRectangles() method. It comes in two versions whose syntaxes are:

public void DrawRectangles(Pen pen, Rectangle[] rects);
public void DrawRectangles(Pen pen, RectangleF[] rects);

This method requires an array of Rectangle or RectangleF values. When executed, it draws individual rectangles using each member of the array as its own rectangle. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Red);
        Rectangle[] Rect = { new Rectangle(20,  20, 120, 20),
	                         new Rectangle(20,  50, 120, 30),
		         new Rectangle(20,  90, 120, 40),
		         new Rectangle(20, 140, 120, 60) };

        e.Graphics.DrawRectangles(penCurrent, Rect);
}

This would produce:

Rectangles

Practical LearningPractical Learning: Drawing a Series of Rectangles

  1. Start a new Windows Application named YearlySales1
  2. Design the form as follows:
     
     
    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 lblCurYear This Year's Sales
    Label Label lblLastYear 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.Text;
    using System.Windows.Forms;
    
    namespace YearlySales1
    {
        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)
    {
                int curQtr1 = 0,
                    curQtr2 = 0,
                    curQtr3 = 0,
                    curQtr4 = 0;
                int prvQtr1 = 0,
                    prvQtr2 = 0,
                    prvQtr3 = 0,
                    prvQtr4 = 0;
    
                // Retrieve the values of the current year's sales
                try
                {
                    curQtr1 = int.Parse(txtCurrentQtr1.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value for the first quater");
                    curQtr1 = 0;
                }
    
                try
                {
                    curQtr2 = int.Parse(txtCurrentQtr2.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value for the second quater");
                    curQtr2 = 0;
                }
    
                try
                {
                    curQtr3 = int.Parse(txtCurrentQtr3.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value for the third quater");
                    curQtr3 = 0;
                }
    
                try
                {
                    curQtr4 = int.Parse(txtCurrentQtr4.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value for the fourth quater");
                    curQtr4 = 0;
                }
    
                // Create an array of Rectangle objects for the current year
                Rectangle[] rectCurrentYear =
                {
                    new Rectangle(txtCurrentQtr1.Left+20,
    	                          380-curQtr1, 40, curQtr1),
                    new Rectangle(txtCurrentQtr2.Left+20,
    	                          380-curQtr2, 40, curQtr2),
                    new Rectangle(txtCurrentQtr3.Left+20,
    	                          380-curQtr3, 40, curQtr3),
                    new Rectangle(txtCurrentQtr4.Left+20,
    	                          380-curQtr4, 40, curQtr4)
                };
    
                // Retrieve the values of last year's sales
                try
                {
                    prvQtr1 = int.Parse(txtPreviousQtr1.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value for the third quater");
                    prvQtr1 = 0;
                }
    
                try
                {
                    prvQtr2 = int.Parse(txtPreviousQtr2.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value for the third quater");
                    prvQtr2 = 0;
                }
    
                try
                {
                    prvQtr3 = int.Parse(txtPreviousQtr3.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value for the third quater");
                    prvQtr3 = 0;
                }
    
                try
                {
                    prvQtr4 = int.Parse(txtPreviousQtr4.Text) / 100;
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid value for the third quater");
                    prvQtr4 = 0;
                }
    
                // Create an array of Rectangle objects for the previous year
                Rectangle[] rectPreviousYear =
                {
                    new Rectangle(txtPreviousQtr1.Left+30,
    	                          380-prvQtr1, 40, prvQtr1),
                    new Rectangle(txtPreviousQtr2.Left+30,
    	                          380-prvQtr2, 40, prvQtr2),
                    new Rectangle(txtPreviousQtr3.Left+30,
    	                          380-prvQtr3, 40, prvQtr3),
                    new Rectangle(txtPreviousQtr4.Left+30,
    	                          380-prvQtr4, 40, prvQtr4)
                };
    
                // In case the user has changed the values,
                // erase the previous chart
                graphDrawingArea.Clear(BackColor);
    
                // Draw the chart for the previous year first to send it back
                graphDrawingArea.DrawRectangles(new Pen(Color.Blue),
                                 rectPreviousYear);
                // Draw the chart for the current year in front
                graphDrawingArea.DrawRectangles(new Pen(Color.Red),
                                 rectCurrentYear);
    
                // Draw the small rectangles of the legend
                graphDrawingArea.DrawRectangle(new Pen(Color.Blue),
                                lblCurYear.Left - 30,
                                lblCurYear.Top, 14, 10);
                graphDrawingArea.DrawRectangle(new Pen(Color.Red),
                                lblLastYear.Left - 30,
                                lblLastYear.Top, 14, 10);
    
                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
     
     
  10. After using it, close the form

Ellipses and Circles

An ellipse is a closed continuous line whose points are positioned so that two points exactly opposite each other have the exact same distant from a central point. It can be illustrated as follows:

Ellipse

Because an ellipse can fit in a rectangle, in GDI+ programming, an ellipse is defined with regards to a rectangle it would fit in. To draw an ellipse, you can use the Graphics.DrawEllipse() method that comes in four versions whose syntaxes are:

public void DrawEllipse(Pen pen,
		     Rectangle rect);
public void DrawEllipse(Pen pen,
		     RectangleF rect);
public void DrawEllipse(Pen pen,
		     int x,
		     int y,
		     int width,
		     int height);
public void DrawEllipse(Pen pen,
		     float x,
		     float y,
		     float width,
		     float height);

The arguments of this method play the same roll as those of the Graphics.DrawRectangle() method:

Ellipse 2

Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Red);

        e.Graphics.DrawEllipse(penCurrent,
                                             new Rectangle(20, 20, 226, 144));
}

Ellipse

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.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.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;
    
                // 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
  7. Close the form
 

Home Copyright © 2007 FunctionX, Inc.