Use DrawPolygon and DrawLines to draw shapes (and understand the different results) in C#

DrawPolygon and DrawLines

The Graphics object’s DrawPolygon method connects the points in an array of Point or PointF to draw a polygon. It automatically draws a line between the first and last points to close the polygon.

The DrawLines method connects the points in an array much as DrawPolygon does except it does not connect the first and last points.

The following code shows how the program draws in the two upper PictureBoxes.

// A series of points (not closed).
private Point[] OpenPoints =
{
    new Point(74, 20),
    new Point(97, 61),
    new Point(134, 41),
    new Point(100, 120),
    new Point(24, 87),
    new Point(9, 36),
    new Point(63, 57),
};

// Draw a polygon from a series of (not closed) points.
private void picPolygon_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    e.Graphics.FillPolygon(Brushes.Yellow, OpenPoints);

    using (Pen big_pen = new Pen(Color.Blue, 10))
    {
        e.Graphics.DrawPolygon(big_pen, OpenPoints);
    }
}

// Draw lines from a series of (not closed) points.
private void picLines_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    e.Graphics.FillPolygon(Brushes.Yellow, OpenPoints);

    using (Pen big_pen = new Pen(Color.Blue, 10))
    {
        e.Graphics.DrawLines(big_pen, OpenPoints);
    }
}

The top two PictureBoxes in this example use DrawPolygon and DrawLines respectively with an array of Points. Notice how DrawLines does not close the polygon.

Even if the first and last points in the array are the same, DrawPolygon and DrawLines do not produce the same result. DrawPolygon treats the meeting of the first and last points as a corner. DrawLines treats them as the place where two unrelated lines meet, so it does not draw a corner.

The bottom two PictureBoxes in this example use DrawPolygon and DrawLines with an array of Points where the first and last points are the same. (The code is similar to the code shown above so it isn’t repeated here. The only difference is in the array of points.)

Notice how DrawLines does not draw the upper middle corner the same way DrawPolygon does.


Download Example   Follow me on Twitter   RSS feed




This entry was posted in drawing, graphics and tagged , , , , , , , , , . Bookmark the permalink.

2 Responses to Use DrawPolygon and DrawLines to draw shapes (and understand the different results) in C#

  1. mohit kumar says:

    How to move drawpoly
    objects

Leave a Reply

Your email address will not be published. Required fields are marked *