This example shows how to draw a Sierpinski carpet, a type of fractal known as a gasket. The posts Draw a Sierpinski gasket in C# and Draw a Sierpinski triangle in C# shows two ways to draw a different kind of gasket.

The key is to Sierpinski’s carpet is the following `DrawRectangle` method.

`// Draw a carpet in the rectangle.
private void DrawRectangle(Graphics gr, int level, RectangleF rect)
{
// See if we should stop.
if (level == 0)
{
// Fill the rectangle.
gr.FillRectangle(Brushes.Blue, rect);
}
else
{
// Divide the rectangle into 9 pieces.
float wid = rect.Width / 3f;
float x0 = rect.Left;
float x1 = x0 + wid;
float x2 = x0 + wid * 2f;
float hgt = rect.Height / 3f;
float y0 = rect.Top;
float y1 = y0 + hgt;
float y2 = y0 + hgt * 2f;
// Recursively draw smaller carpets.
DrawRectangle(gr, level - 1, new RectangleF(x0, y0, wid, hgt));
DrawRectangle(gr, level - 1, new RectangleF(x1, y0, wid, hgt));
DrawRectangle(gr, level - 1, new RectangleF(x2, y0, wid, hgt));
DrawRectangle(gr, level - 1, new RectangleF(x0, y1, wid, hgt));
DrawRectangle(gr, level - 1, new RectangleF(x2, y1, wid, hgt));
DrawRectangle(gr, level - 1, new RectangleF(x0, y2, wid, hgt));
DrawRectangle(gr, level - 1, new RectangleF(x1, y2, wid, hgt));
DrawRectangle(gr, level - 1, new RectangleF(x2, y2, wid, hgt));
}
}`

This method fills a rectangle. It starts by checking the `level` parameter. If `level` is 0, then the method is drawing one of the smallest rectangles. In that case, the method simply draws its rectangle and stops.

If `level` is greater than 0, the method divides its area into a 3 × 3 array of rectangles and then recursively calls itself to draw all but the middle one.

##
About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.