問題描述
我正在尋找一種方法來計算 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
.
背景:我的應用程序中有可能重疊的 Shape
.我想知道一個 Shape
與另一個重疊多少.Shape
可能會傾斜、旋轉等.如果我有一個函數 area(Shape)
(或 Area
),我可以使用兩個 Shape
的交集如下:
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);
}
推薦答案
一種方法是 fill()
每個都按比例縮放和 轉換 Shape
使用合適的 AlphaComposite
和計算底層 中的重疊像素光柵
.
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
.
附錄1:使用這個計算器查看AlphaComposite.Xor
表明任意兩種不透明顏色的交集為零.
Addendum 1: Using this calculator to see the effect of AlphaComposite.Xor
shows that the intersetion of any two opaque colors is zero.
附錄2:計數像素可能存在性能問題;采樣可能會有所幫助.如果每個 Shape
是相當凸的,可以從 intersect()
面積為 的面積之和Shape
s' getBounds2D()
.例如,
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 Shape
s' 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.
這篇關于如何計算 java.awt.geom.Area 的面積?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!