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);
}
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.
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.
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:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With