The *Mathematica* graphics language has a Polygon primitive, but (as of *Mathematica* 7) there is no way to create a Polygon with holes punched out (more specifically, any polygon with two or more contours). However, there is a fairly good way to fake this feature.

- Draw the first polygon contour.
- Draw a line from the ending point of the first contour to the starting point of the second contour.
- Draw the second polygon contour.
- Repeat steps 1-3 for N contours
- Once all contours are drawn, draw a line from the ending point of contour N-1, then N-2, ..., all the way back to contour 1. These are the same ending points we used earlier, except in reverse order.

MultiContourPolygon[polys_List] := Module[

{contours=Append[#, First[#]]&/@polys},

{

Polygon@Join[Join@@contours, Reverse[First/@contours]],

Line[contours]

}

]

{contours=Append[#, First[#]]&/@polys},

{

Polygon@Join[Join@@contours, Reverse[First/@contours]],

Line[contours]

}

]

Graphics@MultiContourPolygon[{

{{0, 0}, {0, 1}, {1, 1}, {1, 0}},

{{.25, .25}, {.75, .25}, {.75, .75}, {.25, .75}},

{{.4, .4}, {.6, .4}, {.6, .6}, {.4, .6}}

}]

{{0, 0}, {0, 1}, {1, 1}, {1, 0}},

{{.25, .25}, {.75, .25}, {.75, .75}, {.25, .75}},

{{.4, .4}, {.6, .4}, {.6, .6}, {.4, .6}}

}]

Mathematica's built-in PDF import feature uses this same algorithm to represent arbitrary multi-contoured paths from PDF files.

Import["ExampleData/mathematica.pdf"]

## 3 comments:

Thank you for the info, it was really helpful! And it can be extended to 3-D by just setting the points in 3 dimensions!

Good post. Thank you.

For computations that depend on the edges of the polygon, such as intersection calculations, this isn't idea, but it gets the job done in many cases.

Post a Comment