[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.