[localhost:~]$ cat * > /dev/ragfield

Wednesday, March 18, 2009

Polygons with holes in Mathematica

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.

  1. Draw the first polygon contour.
  2. Draw a line from the ending point of the first contour to the starting point of the second contour.
  3. Draw the second polygon contour.
  4. Repeat steps 1-3 for N contours
  5. 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]
    }
]
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}}
}]
Polygons with holes

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

Import["ExampleData/mathematica.pdf"]
Polygons with holes 2

Download Mathematica notebook

3 comments:

Anonymous said...

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!

dude said...
This comment has been removed by the author.
dude said...

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.