Home

Drawing Curves

 

Curves

 

Introduction to Curves

A curve is a line that joins two or more points. If only two points are involved, the line would join them but the line is not straight. If there are three points A, B, and C, the line would start on the first point A, cross the second point B, and stop at the last point C. If more than three points are involved, the line would start on the first, cross the second, cross the third and each line before stopping on the last. The points of a curve don't have to be aligned. In fact, the whole idea of drawing a curve is to have a non-straight line that joins different non-aligned points. This can be illustrated with the following three curves labeled C1, C2, and C3:

The first curve, C1, includes only two points. The second, C2 includes three points. The third, C3, includes four points.

The section between two points is called a segment. This also means that a curve can be distinguished by the number of segments it has. If a curve is made of only two points, this means that it has only one segment from the first to the second, which is the last, point. If a curve includes three points, it has two segments. The first segment spans from the first point to the second point and the second segment spans from the second point to the third point. Based on this, the number of segments of a curve is equal to the number of its points - 1.

A curve can be drawn in GDI+ using the Graphics.DrawCurve() method. When drawing a curve, you must specify how many points would be involved. This means that you can first declare an array of Point or PointF values. Because it is left up to you to decide on this issue, the Graphics class provides the following syntaxes of the DrawCurve() method:

public void DrawCurve(Pen pen, Point[] points);
public void DrawCurve(Pen pen, PointF[] points);

This version of the method takes an array of Point or PointF values as arguments. The number of members of the array depends on you. Here is an example that uses four points to draw a curve with three segments:

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.Blue);
        Point[] pt = { new Point( 40,  42),
	              new Point(188, 246),
                              new Point(484, 192),
	              new Point(350,  48) };

        e.Graphics.DrawCurve(penCurrent, pt);
    }
}

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

        return 0;
    }
}

This would produce:

Curve

As you can see, when the curve is drawn, a bent line crosses the intermediary points between the first and the last. To make the lines non-straight, the compiler uses a value called tension used to bend the line. If you want, you can specify the bending factor that should be applied. To do this, you would use the following version of the DrawCurve() method:

public void DrawCurve(Pen pen,
		   Point[]points, 
		   float tension);
public void DrawCurve(Pen pen, 
		   PointF[] points, 
		   float tension);

The amount of bending to apply is passed as the tension argument. It can be passed as a decimal value >= 0.00. If this value is passed as 0.00, the lines would be drawn straight. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Blue);
        Point[] pt = { new Point(40,  42),
	              new Point(188, 246),
                              new Point(484, 192),
	              new Point(350,  48) };

        e.Graphics.DrawCurve(penCurrent, pt, 0.00F);
}

Curve

This means that, if you want a real curve, either you don't pass the tension argument and use the first version of the method or you pass the tension argument as a value higher than 0.00. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Blue);
        Point[] pt = { new Point(40,  42),
	              new Point(188, 246),
                              new Point(484, 192),
	              new Point(350,  48) };

        e.Graphics.DrawCurve(penCurrent, pt, 2.15F);
}

This would produce:

A curve with a tension value of 2.15

Both versions of the DrawCurve() method that we have used allow you to start the curve on the first point. Consider the following example that draws a curve of five points resulting in four segments:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Blue);
        PointF[] pt = { new PointF(20.00F,  322.00F),
		new PointF(124, 24),
	            	new PointF(214, 242), 
		new PointF(275,  28),
         	    	new PointF(380.00F,  322.00F) };

        e.Graphics.DrawCurve(penCurrent, pt);
}

This would produce:

Curve

If you want, you can start the curve on any point instead of the first. To support this, the Graphics class provides the following version of the DrawCurve() method:

public void DrawCurve(Pen pen, 
	           PointF[] points, 
	           int offset, 
	           int numberOfSegments);

The offset argument allows you to specify how many points should be skipped before starting to draw. The first conclusion is that the value of the offset must be 0 or higher. If you pass this argument as 0, the curve would be drawn from the first point. If you pass this argument as 1, the first point would not be considered in the curve. This means that the drawing of the curve would start on the second point and so on. If you pass it as 2, the first and the second point would not be part of the curve, meaning that the curve would start on the third point. 

After the curve has started from the point you specify using the offset argument, you can then specify how many segments of the curve would be drawn. This number must be lower than the number of available segments, that is after subtracting the offset value from the total number of segments of the array. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Blue);
        PointF[] pt = { new PointF(20.00F,  322.00F),
			   new PointF(124, 24),
	            	   new PointF(214, 242), 
			   new PointF(275,  28),
                    	   new PointF(380.00F,  322.00F) };

        e.Graphics.DrawCurve(penCurrent, pt, 1, 2);
}

This would produce:

A curve with an offset value and a limited number of segments

Once again, the compiler arranges to apply a tension when drawing the curve. If you would prefer to use straight lines or to apply a different tension than the default, you can use the following version of the Graphics.DrawCurve() method:

public void DrawCurve(Pen pen, 
		   Point[] points, 
		   int offset, 
		   int numberOfSegments, 
		   float tension);
public void DrawCurve(Pen pen, 
		   PointF[] points, 
		   int offset, 
		   int numberOfSegments, 
		   float tension);

This time, you can pass the value of the tension as 0 to get straight lines:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Blue);
        PointF[] pt = { new PointF(20.00F,  322.00F),
			   new PointF(124, 24),
	                   new PointF(214, 242),
			   new PointF(275,  28),
                	   new PointF(380.00F,  322.00F) };

        e.Graphics.DrawCurve(penCurrent, pt, 0, 4, 0);
}

This would produce:

Curve

Or you can pass the tension with any positive value of your choice. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Blue);
        PointF[] pt = { new PointF(20.00F,  322.00F), new PointF(124, 24),
	                   new PointF(214, 242), new PointF(275,  28),
                    	   new PointF(380.00F,  322.00F) };

        e.Graphics.DrawCurve(penCurrent, pt, 1, 3, 1.750F);
}

This would produce:

Curve

 

A Bézier Curve

A bézier curve is a continuous line that is drawn using four points that are not necessarily aligned. It can be illustrated as follows:

Bezier

To draw this line (with four points), the compiler would draw a curve from the first point to the fourth point. Then it would bend the curve by bringing each middle (half-center) side close to the second and the third points respectively, without touching those second and third points. For example, the above bézier curve could have been drawn using the following four points:

Bezier Illustration

To draw a bézier curve, the Graphics class provides the DrawBezier() method that is overloaded in three versions whose syntaxes are:

public void DrawBezier(Pen pen,
                    Point pt1,
                    Point pt2,
                    Point pt3,
                    Point pt4);
public void DrawBezier(Pen pen,
                    PointF pt1,
                    PointF pt2,
                    PointF pt3,
                    PointF pt4);
public void DrawBezier(Pen pen,
                    float x1,
                    float y1,
                    float x2,
                    float y2,
                    float x3,
                    float y3,
                    float x4,
                    float y4);

Based on this, to draw a bézier line, you can use either four Point or PointF values or the coordinates of the four points. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Blue);
        Point pt1 = new Point(20, 12),
                    pt2 = new Point(88, 246),
                    pt3 = new Point(364, 192),
                    pt4 = new Point(250, 48);

        e.Graphics.DrawBezier(penCurrent, pt1, pt2, pt3, pt4);
}

This would produce:

Bezier Curve

A Series of Bézier Curves

The Graphics.DrawBezier() method is used to draw one bézier curve. If you want to draw many bézier curves, you can call the Graphics.DrawBeziers() method that is overloaded in two versions as follows:

public void DrawBeziers(Pen pen, Point[] points);
public void DrawBeziers(Pen pen, PointF[] points);

The DrawBeziers() method requires an array of Point of PointF values. When working with only four coordinates, the DrawBeziers() method works exactly like DrawBezier(), the different is that, while DrawBezier() expects four Point or four PointF values, DrawBeziers() expects an array of Point or PointF values. Using, DrawBeziers(), the above bézier curve can be drawn as follows and produce the same result:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Blue);
        Point[] pt = { new Point(20,  12), new Point(88, 246),
		          new Point(364, 192), new Point(250,  48) };

        e.Graphics.DrawBeziers(penCurrent, pt);
}

This would produce:

Curve

A characteristic of using DrawBeziers() is that it allows you to draw a bézier curve using 7 Point or PointF values. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Blue);
        Point[] pt = { new Point( 10,  5), new Point(340, 60),
                          new Point(320, 148), new Point(150, 120),
	                  new Point(24, 220), new Point(250, 150),
	                  new Point(304, 240) };

        e.Graphics.DrawBeziers(penCurrent, pt);
}

This would produce:

Beziers
 

A Closed Curve

If you use either the DrawLines(), the DrawBezier() or the DrawBeziers() methods, you would get a continuous line or a series of lines that has a beginning and an end. Alternatively, GDI+ allows you to draw a series of lines but join the end of the last line to the beginning of the first line to have a closed shape. To draw this figure, you can call the Graphics.DrawClosedCurve() method that is overloaded in four versions. Two of them have the following syntaxes:

public void DrawBeziers(Pen pen, Point[] points);
public void DrawClosedCurve(Pen pen, PointF[] points);

These two versions are the easiest to use. They allow you to provide an array of four Point or four PointF values. When executed, each of these methods draws a curve that passes through each coordinate and closes the curve by joining the end point to the first unless both points are the same. Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Blue);
        Point[] pt = { new Point(40,  42), new Point(188, 246),
                          new Point(484, 192), new Point(350,  48) };

        e.Graphics.DrawClosedCurve(penCurrent, pt);
}

This would produce:

Closed Curve

The first two versions are used to draw the lines but curve them in order to make the shape appear smooth. If you want, you can draw the lines straight from one point to the next without curving them. Using this scenario, the above shape would appear as follows:

Closed Shape With Straight Lines

To draw this type of shape using the DrawClosedCurve() method, you can use one of the following versions of the method:

public void DrawClosedCurve(Pen pen, 
			 Point[] points, 
			 float tension, 
			 FillMode fillmode);
public void DrawClosedCurve(Pen pen, 
			 PointF[] points, 
			 float tension, 
			 FillMode fillmode);

These versions allow you to specify the tension and the fill mode. The tension factor allow you to specify how much curve would be applied. If this value is passed as 0.00, the points would be joined with straight lines. Otherwise, you can apply a tension using an appropriate decimal value.

The fillmode factor determines how the interior of the curve would be filled. It is controlled through the FillMode enumerator that is defined in the System.Drawing.Drawing2D namespace. The FillMode enumerator has two members: Alternate and Winding. Here is an example:

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)
    {
        Pen penCurrent = new Pen(Color.Red);
        Point[] pt = { new Point(40,  42), new Point(188, 246),
                          new Point(484, 192), new Point(350,  48) };

        e.Graphics.DrawClosedCurve(penCurrent, pt, 0.75F,
                     FillMode.Winding);
    }
}

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

        return 0;
    }
}

This would produce:

Closed Curve

Remember that the higher the tension, the sharper the corners. If you want the shape to show straight lines, pass a tension of 0.00F.

Pies

A pie is a fraction of an ellipse delimited by a starting angle and an angle that constitutes the desired portion to make up a pie. It can be illustrated as follows:

Pie Illustration

To draw a pie, you can use the Graphics.DrawPie() method that comes in various versions as follows:

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

A pie is based on an ellipse (like an arc). The ellipse would fit in a rectangle passed as the rect argument. The rectangle can also be specified by its location (x, y) and its dimensions (width and height).

Inside of the parent rectangle in which an ellipse would be drawn, you set a starting angle. This angle is measured from 0 up counted clockwise (like the numbers of an analog clock). This means that an angle of 90 represents 6 o'clock and not 12 o'clock. This starting angle is passed as the startAngle argument.

After specifying the starting angle, you must specify the amount of angle covered by the pie. This also is measured clockwise. This value is passed as the sweepAngle argument.

Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Red);
        e.Graphics.DrawPie(penCurrent, 20, 20, 200, 100, 45, 255);
}

This would produce:

Pie

Practical LearningPractical Learning: Drawing an Ellipse

  1. Start Microsoft Visual C# and create a new Windows Application named SchoolEnrolment1
  2. Design the form as follows:
     
    School Enrolment
    Control Name Text
    Label Label   Enrolment / Program ___________________________
    Label Label   Graduates
    Label Label   Undergraduates
    Label Label   Certificates
    TextBox TextBox txtGraduates 0
    TextBox TextBox txtUndergraduates 0
    TextBox TextBox txtCertificates 0
    Button Button btnCreateChart Create Chart
    PictureBox PictureBox pbxChart  
    Label Label   ____Legend____
    Label Label lblGraduates Graduates
    Label Label lblUndergraduates Undergraduates
    Label Label lblCertificates Certificates
    Button Button btnClose Close
  3. Right-click the form and click View Code
  4. Declare three variables 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 SchoolEnrolment1
    {
        public partial class Form1 : Form
        {
            float Graduates;
            float Undergraduates;
            float Certificates;
    
            public Form1()
            {
                InitializeComponent();
            }
        }
    }
  5. Return to the form and click an unoccupied area of its body. In the Properties window, click the Events button Events
  6. Double-click the Paint field and implement the event as follows:
     
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
                pbxChart.CreateGraphics().DrawEllipse(new Pen(Color.Red),
                                  new Rectangle(0,  0, 260, 200));
                pbxChart.CreateGraphics().DrawPie(new Pen(Color.Blue),
                                   0.0F, 0.0F, 260.0F, 200.0F, 0.0F, Graduates);
                pbxChart.CreateGraphics().DrawPie(new Pen(Color.Green),
                                          0.0F, 0.0F, 260.0F,
                            200.0F, Graduates, Undergraduates);
                pbxChart.CreateGraphics().DrawPie(new Pen(Color.Fuchsia),
                                          0.0F, 0.0F, 260.0F,
                              200.0F, Graduates + Undergraduates,
                                  Certificates);
    
                e.Graphics.DrawEllipse(new Pen(Color.Blue),
                                      new Rectangle(lblGraduates.Left,
                                    lblGraduates.Top + 20,
                            lblUndergraduates.Width,
                            20));
    
                e.Graphics.DrawEllipse(new Pen(Color.Green),
                                      new Rectangle(lblUndergraduates.Left,
                                    lblUndergraduates.Top + 20,
                            lblUndergraduates.Width,
                            20));
    
                e.Graphics.DrawEllipse(new Pen(Color.Fuchsia),
                                      new Rectangle(lblCertificates.Left,
                                    lblCertificates.Top + 20,
                            lblUndergraduates.Width,
                                20));
    }
  7. Return to the form and click the picture box
  8. In the Events section of the Properties window, double-click Paint and implement its event as follows:
     
    private void pbxChart_Paint(object sender, PaintEventArgs e)
    {
                Invalidate();
    }
  9. Return to the form and double-click the Create Chart button
  10. Implement the event as follows:
     
    private void btnCreateChart_Click(object sender, EventArgs e)
    {
                float grad = 0.00F,
                      under = 0.00F,
                      cert = 0.00F,
                      total = 0.00F;
                float percentGraduates,
                  percentUndergraduates,
                  percentCertificates;
    
                try
                {
                    grad = float.Parse(txtGraduates.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid graduate value");
                }
    
                try
                {
                    under = float.Parse(txtUndergraduates.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid graduate value");
                }
    
                try
                {
                    cert = float.Parse(txtCertificates.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid graduate value");
                }
    
                total = grad + under + cert;
                percentGraduates = (grad / total) * 100;
                percentUndergraduates = (under / total) * 100;
                percentCertificates = (cert / total) * 100;
    
                Graduates = (360 * percentGraduates) / 100;
                Undergraduates = (360 * percentUndergraduates) / 100;
                Certificates = (360 * percentCertificates) / 100;
    
                pbxChart.Invalidate();
    }
  11. Execute the application and test the form
     
     School Enrolment
  12. After using it, close the form

Arcs

An arc is a portion or segment of an ellipse, meaning an arc is a non-complete ellipse. While a pie is a closed shape, an arc is not: it uses only a portion of the line that defines an ellipse. Because an arc must confirm to the shape of an ellipse, it is defined as it fits in a rectangle and can be illustrated as follows:

Arc

To support arcs, the Graphics class is equipped with the DrawArc() method that is provided in four versions whose syntaxes are:

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

The ellipse that would contain the arc must be drawn in a Rectangle or a RectangleF rect. You can also define that ellipse by the coordinates of its inscribed rectangle x, y, and its dimensions width, height.  Besides the borders of the rectangle in which the arc would fit, an arc must specify its starting angle, startAngle, measured clockwise from the x-axis its starting point. An arc must also determine its sweep angle measured clockwise from the startAngle parameter to the end of the arc. These two value follow the same definitions we reviewed for the Graphics.Pie() method.

Here is an example:

private void Exercise_Paint(object sender, PaintEventArgs e)
{
        Pen penCurrent = new Pen(Color.Red);
        e.Graphics.DrawArc(penCurrent, 20, 20, 200, 150, 225, 200);
}

Arc

 
 

Previous Copyright © 2008-2009, yevol.com Next