using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace WpfRenderShapes
{
    public static class DrawingContextExtensions
    {
        // Draw a polygon.
        public static void DrawPolygon(this DrawingContext drawingContext,
            Brush brush, Pen pen, Point[] points, FillRule fillRule)
        {
            drawingContext.DrawPolygonOrPolyline(brush, pen, points, fillRule, true);
        }

        // Draw a polyline.
        public static void DrawPolyline(this DrawingContext drawingContext,
            Brush brush, Pen pen, Point[] points, FillRule fillRule)
        {
            drawingContext.DrawPolygonOrPolyline(brush, pen, points, fillRule, false);
        }

        // Draw a polygon or polyline.
        private static void DrawPolygonOrPolyline(this DrawingContext drawingContext,
            Brush brush, Pen pen, Point[] points, FillRule fillRule, bool drawPolygon)
        {
            // Make a StreamGeometry to hold the drawing objects.
            StreamGeometry geo = new StreamGeometry();
            geo.FillRule = fillRule;

            // Open the context to use for drawing.
            using (StreamGeometryContext context = geo.Open())
            {
                // Start at the first point.
                context.BeginFigure(points[0], true, drawPolygon);

                // Add the points after the first one.
                context.PolyLineTo(points.Skip(1).ToArray(), true, false);
            }

            // Draw.
            drawingContext.DrawGeometry(brush, pen, geo);
        }
    }
}
