How to calculate the area of a java.awt.geom.Area?(如何计算 java.awt.geom.Area 的面积?)
问题描述
我正在寻找一种方法来计算 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 的面积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何计算 java.awt.geom.Area 的面积?


基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01