Home

Drawing Shapes

 

GDI+ Tools: The Pen

 

Introduction

The most basic tool you can use is the pen. The GDI+ library provides a pen through the Pen class.

Creating a Pen

To obtain a pen, you can declare a variable of type Pen using one of the constructors of its class.

 

Characteristics of a Pen

 

The Color of a Pen

The primary piece of information you must specify about a pen is its color. To do this, you can use the following constructor: 

public Pen(Color color);

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 pnBorder;
        Color clr = Color.Violet;
        pnBorder = new Pen(clr);
    }
}

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

        return 0;
    }
}

Instead of first declaring a Color variable, you can directly define the color in the constructor.

If you just want to create a regular pen whose only known characteristic would be its color, the System.Drawing namespace provides the Pens class. The primary, and in fact only, role of the Pens class is to define a simple pen and only specify its color. To make this possible, the Pens class is equipped with only static properties that each represents the name of a color. The names are those of common colors (such as Red, Green, Blue, Yellow, Violet, et), the colors used on web pages (such as LightBlue or DarkGreen), the colors defined in Microsoft Windows (such as ActiveBorder, AppWorkspace, or ButtonFace, etc), and many others. When accessing a Pens property, it produces a Pen object. This means that you can access a pen to initialize a Pen variable. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        pnBorder = Pens.Lavender;
}

If you have already created a pen, to change its color, you can assign the desired color name or color value to the Pen.Color property.

The Width of a Pen

The simplest pen is meant to draw a tinny line. Here is an example of a line drawn with a simple pen:

Line

Such a simple pen is said to have a width of 1 pixel. To give you the ability to support or modify the width of a pen, the Pen class is equipped with a Width property.

When creating a pen, to specify is width, you can use the following constructor:

public Pen(Color color, float width);

While the first argument represents the color as we saw in the previous section, the second argument specifies the width, which must be a floating-point value. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen pnBorder = new Pen(Color.Tomato, 5.0F);
}

If you have already defined a pen and you want to change its width, the Pen class provides the Width property. Using this property, to modify the width of a pen, assign a floating-point number to its Width property. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen pnBorder = new Pen(Color.Brown);
        // Do something, if necessary
        pnBorder.Width = 3.00F;
        // Do something, if necessary
}

In the same way, you can change, increase, or decrease the width of a pen as often as you want. Here are examples:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen pnBorder = new Pen(Color.Brown);
        // Do something, if necessary
        pnBorder.Width = 3.00F;
        // Do something, if necessary
        pnBorder.Width = 6.00F;
        // Do something, if necessary
        pnBorder.Width = 12.00F;
        // Do something, if necessary
        pnBorder.Width = 26.00F;
        // Do something, if necessary
        pnBorder.Width = 44.00F;
        // Do something, if necessary
}

We may get the following result:

If a pen has already been defined and you want to know its width, get the value of its Width property.

The Start and End Caps

If you use a pen with a small width, such as 1 pixel, you may not notice how a line drawn with it starts but with a significantly wide pen, you would notice that it starts with a flat shape. An alternative is to have round, square, or triangle start. This is referred to as the start cap.

To support the starting shape of a line, the Pen class is equipped with a property named StartCap. The Pen.StartCap property is of based on the LineCap enumeration whose members are: AnchorMask, ArrowAnchor, Custom, DiamondAnchor, Flat, NoAnchor, Round, RoundAnchor, Square, SquareAnchor, and Triangle. To specify the start cap, assign the desired LineCap member to the StartCap property of the pen. Here are examples:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen pnBorder = new Pen(Color.Brown);
        pnBorder.Width = 12.00F;
        pnBorder.StartCap = System.Drawing.Drawing2D.LineCap.AnchorMask;
        // Do something, if necessary
        pnBorder.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
        // Do something, if necessary
        pnBorder.StartCap = System.Drawing.Drawing2D.LineCap.DiamondAnchor;
        // Do something, if necessary
        pnBorder.StartCap = System.Drawing.Drawing2D.LineCap.Flat;
        // Do something, if necessary
        pnBorder.StartCap = System.Drawing.Drawing2D.LineCap.NoAnchor;
        // Do something, if necessary
        pnBorder.StartCap = System.Drawing.Drawing2D.LineCap.Round;
        // Do something, if necessary
        pnBorder.StartCap = System.Drawing.Drawing2D.LineCap.RoundAnchor;
        // Do something, if necessary
        pnBorder.StartCap = System.Drawing.Drawing2D.LineCap.Square;
        // Do something, if necessary
        pnBorder.StartCap = System.Drawing.Drawing2D.LineCap.SquareAnchor;
        // Do something, if necessary
        pnBorder.StartCap = System.Drawing.Drawing2D.LineCap.Triangle;
        // Do something, if necessary
}

These may produce the following results:

If none of the available members of the LineCap enumeration suits you, you can define a custom cap using the CustomStartCap class.

You can also control the end cap of a line. To support this, the Pen class is equipped with a property named EndCap that also is based on the LineCap enumeration with the same value. Using a combination of the start and end caps, you can control how a line starts and how it ends. If none of the available members of the LineCap enumeration suits you, you can define a custom cap using the CustomEndCap class.

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.Linq;
    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.Linq;
    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.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;
    
                // 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

Lines

 

A Line

A line is a junction of two points. This means that a line has a beginning and an end:

Line Definition

The beginning and the end are two distinct points. Based on this, a line is represented either with two Point values or by four numbers representing its values on the Cartesian axes. To draw a line, the Graphics class is equipped with the following overloaded DrawLine() method: 

public void DrawLine(Pen pen,
		  Point pt1,
		  Point pt2);
public void DrawLine(Pen pen,
		  PointF pt1,
		  PointF pt2);
public void DrawLine(Pen pen,
		  int x1,
		  int y1,
		  int x2,
		  int y2);
public void DrawLine(Pen pen,
		  float x1,
		  float y1,
		  float x2,
		  float y2);

If the line is represented with natural numbers, its origin can be specified as a Point pt1 and its end would be represented with a Point pt2. If the line is drawn using floating numbers, you can start it at one PointF pt1 and end it at another PointF pt2. Otherwise, you can specify the starting point with coordinates (x1, y1) and the end would be represented with coordinates (x2, y2). The same type of line can be drawn using decimal values from coordinates (x1, y1) to coordinates (x2, y2).

Here is an example that draws three lines:

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

        penCurrent = new Pen(Color.Green, 3.50F);
        e.Graphics.DrawLine(penCurrent, 40, 40, 225, 40);

        penCurrent = new Pen(Color.Blue, 7.25F);
        e.Graphics.DrawLine(penCurrent, 30, 60, 215, 60);
}

Line

 

A Series of Lines

The above DrawLine() method is used to draw one line. If you intend to draw a group of lines at once, you can use the Graphics.DrawLines() method. It is overloaded with two versions as follows:

public  void DrawLines(Penpen, Point[] points);
public void DrawLines(Penpen, PointF[] points);

To use this method, you should first define an array of either Point for natural numbers that represent Cartesian coordinates or PointF for floating numbers. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Point[] Coordinates = { new Point(20, 10), new Point(205, 20),
                                new Point(40, 40), new Point(225, 60),
                                new Point(30, 80), new Point(215, 100) };

        Pen penCurrent = new Pen(Color.Red);
        e.Graphics.DrawLines(penCurrent, Coordinates);
}

This would produce:

Drawing Lines

 

Polygons

A polygon is a series of connected lines with the whole shape being closed. In other words, a polygon is defined a group of lines so that, except for the first line of the group, the starting point of each line is the same as the end point of the previous line and the end point of the last line is connected to the start point of the first line.

To draw a polygon, you can use the Graphics.Polygon() method. It is overloaded with two versions as follows:

public void DrawPolygon(Penpen, Point[] points);
public void DrawPolygon(Penpen, PointF[] points);

To use this method, you can first declare a Point or PointF array and pass it as the second argument to the method. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Point[] Pt = { new Point(20, 50), new Point(180, 50), new Point(180, 20),
                              new Point(230, 70), new Point(180, 120), new Point(180, 90),
       	              new Point(20,  90) };

        Pen penCurrent = new Pen(Color.Red);
        e.Graphics.DrawPolygon(penCurrent, Pt);
}

This would produce:

Polygon
 
 

Previous Copyright 2008-2009, yevol.com Next