Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

swing - 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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...