javaswinggeometry

How to calculate the area of a java.awt.geom.Area?


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 Shapes in my applications that may overlap. I want to know how much one Shape overlaps another. The Shapes may be skewed, rotated, etc. If I had a function area(Shape) (or Area), I could use the intersection of two Shapes like so:

double fractionObscured(Shape bottom, Shape top) {
    Area intersection = new Area(bottom);
    intersection.intersect(new Area(top));
    return area(intersection) / area(bottom);
}

Solution

  • One approach would be to fill() each scaled and transformed Shape with a different color using a suitable AlphaComposite and count the overlapping pixels in the underlying Raster.

    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 the intersect() area to the sum of the areas of the Shapes' getBounds2D(). For example,

    Shape s1, s2 ...
    Rectangle2D r1 = s1.getBounds2D();
    Rectangle2D r2 = s2.getBounds2D();
    Rectangle2D r3 = new Rectangle2D.Double();
    Rectangle2D.intersect(r1, r2, r3);
    double overlap = area(r3) / (area(r1) + area(r2));
    ...
    private double area(Rectangle2D r) {
        return r.getWidth() * r.getHeight();
    }
    

    You may need to validate the results empirically.