问题
I am currently trying to draw and fill a Polygon which has a hole in it in Java. Normally this would not be a big problem, since I would draw the exterior ring and then draw the interior ring with the color of the background.
But the problem is, that the polygon is displayed above a image which should be "seen" through the hole.
I am writing the code in Java and am using JTS Topology Suite for my geometry data.
This is my current code, which just paints the border and fills the polygon with a color.
private void drawPolygon(com.vividsolutions.jts.geom.Polygon gpoly, Color color, Graphics2D g2d){
java.awt.Polygon poly = (java.awt.Polygon)gpoly;
for(Coordinate co : gpoly.getExteriorRing().getCoordinates() {
poly.addPoint(co.x, co.y);
}
g2d.setColor(col);
g2d.fill(poly);
g2d.setColor(Color.BLACK);
g2d.draw(poly);
}
Sadly java.awt.Polygon does not support Polygons with holes.
回答1:
- Use the
Polygon
as the basis for anArea
(e.g. calledpolygonShape
). - Create an
Ellipse2D
for the 'hole', then establish anArea
for it (ellipseShape
). Use Area.subtract(Area) something like:
Area polygonWithHole = polygonShape.subtract(ellipseShape);
回答2:
There are some ways to draw shapes or areas that are more complex than a simple polygon (another answer already mentioned Area
).
Besides those, you could try to tessellate your final polygon. There are lots of algorithms to do this. For more complex shapes, the algorithms get a bit more complex as well. Basically, you're dividing your final shape into little polygons (usually triangles, but it also can be something else) and then draw those polygons.
You can take a look at your possibilities by searching for "Tessellation Algorithm", there are also some already implemented libraries for Java.
回答3:
You can use java.awt.geom.Path2D to render a "compound shape" with a hole in it:
If you have
java.awt.Shape
objects defining the outside & inside edges of the shape, useappend(shape, false)
to add each shape.If you have a set of path points for the outside edge and a set of path points for the inside edge, use
lineTo()
to add the first set of points - creating a closed loop by either ending with the same point you started with, or callingclosePath()
to automatically close the loop. Then usemoveTo()
to create a break before adding the inner set of points via morelineTo()
calls.
In either case, you must create the path passing Path.WIND_NON_ZERO
to the constructor - otherwise the hole won't be left unfilled.
See How to create shape with a hole? for a longer code example.
回答4:
You could fill the polygon first, and then draw the holes on top, giving the illusion that it filled everything but the holes.
来源:https://stackoverflow.com/questions/33239876/java-how-to-draw-and-fill-a-polygon-which-has-holes