I am looking for a way to calculate the area, in pixels, of an arbitrary instance of java.awt.geom.Area
.
The background: I have Shape
s in my applications that may overlap. I want to know how much one Shape
overlaps another. The Shape
s may be skewed, rotated, etc. If I had a function area(Shape)
(or Area
), I could use the intersection of two Shape
s like so:
double fractionObscured(Shape bottom, Shape top) {
Area intersection = new Area(bottom);
intersection.intersect(new Area(top));
return area(intersection) / area(bottom);
}
One approach would be to
fill()
each scaled and transformedShape
with a different color using a suitableAlphaComposite
and count the overlapping pixels in the underlyingRaster
.Addendum 1: Using this calculator to see the effect of
AlphaComposite.Xor
shows that the intersetion of any two opaque colors is zero.Addendum 2: Counting pixels may have performance problems; sampling may help. If each
Shape
is reasonably convex, it may be possible to estimate the overlap from the ratio of theintersect()
area to the sum of the areas of theShape
s'getBounds2D()
. For example,You may need to validate the results empirically.
I would comment if I could. Suraj, your algorithm is correct, but the code should be
In your code last vertice is not taken into account. Just a small edit :)
I've used this class to approximate the area of a shape in one of my projects. It's slow but at high resolution it may still be faster than counting pixels (because the cost of counting pixels grows quadratically with resolution, but the number of line segments on the perimeter grows linearly.)
To find the area of a polygon using the following snippet:
Here n is the total number of vertices and x[i] and y[i] are the x and y coordinates of a vertex i. Note that for this algorithm to work, the polygon must be closed. It doesent work on open polygons.
You can find mathematical alogrithms related to polygons here. You need to convert it to code yourself:)