Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 695
iter Avatar asked Feb 14 '10 23:02

iter


People also ask

What is Area in Java?

An Area object stores and manipulates a resolution-independent description of an enclosed area of 2-dimensional space. Area objects can be transformed and can perform various Constructive Area Geometry (CAG) operations when combined with other Area objects.

What is Java AWT geom?

geom Description. Provides the Java 2D classes for defining and performing operations on objects related to two-dimensional geometry. Some important features of the package include: classes for manipulating geometry, such as AffineTransform and the PathIterator interface which is implemented by all Shape objects.


1 Answers

To find the area of a polygon using the following snippet:

int sum = 0;
for (int i = 0; i < n -1; i++)
{
    sum = sum + x[i]*y[i+1] - y[i]*x[i+1];
}
// (sum / 2) is your area.
System.out.println("The area is : " + (sum / 2));

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:)

like image 54
Suraj Chandran Avatar answered Oct 20 '22 00:10

Suraj Chandran