[英]How to optimize this code to make just the outline of an array of circles show?
I have an array of a Unit object and the unit object has center cx, cy, and radius cr. 我有一个Unit对象的数组,单位对象有中心cx,cy和radius cr。 I want just the outline of the circles to show (think a ven diagram without the overlapping bits).
我想只显示圆圈的轮廓(想想没有重叠位的静脉图)。 I managed to do it, but it makes it extremely slow as it is a nested for loop.
我设法做到了,但它使它非常慢,因为它是一个嵌套的for循环。 Here is the code:
这是代码:
(this is all in a method that cycles through all the units) (这是循环遍历所有单位的方法)
ArrayList<Integer> validangles = new ArrayList<Integer>();
public void getValidAngles(ArrayList<Unit> units) { //get all the angles that aren't overlapping
ArrayList<Integer> invalidAngles = new ArrayList<Integer>();
for (int i = 0; i < units.size(); i++) { //cycle through all other units
Unit c2 = units.get(i);
if (this != c2) { //make sure it is not the same unit
for (int ia = 0; ia < 360; ia += 10) { //cycle through the angles
double ca = Math.toRadians(ia);
Point p = new Point( //point on the circle
(int) Math.round((c2.getCx() + (cr * Math.cos(ca)))),
(int) Math.round((c2.getCy() + (cr * Math.sin(ca)))));
if (overlapping(p)) {
invalidAngles.add(ia-180); //this angle should not be shown
}
}
}
}
validangles.clear();
for (int i = 0; i < 360; i += 10) {
if (!invalidAngles.contains(i-180)) {
validangles.add(i-180);
}
}
}
public void drawValidAngles(Graphics g2) {
for(int i : validangles) {
int x = (int)Math.round(cx+cr*Math.cos(Math.toRadians(i)));
int y = (int)Math.round(cy+cr*Math.sin(Math.toRadians(i)));
g2.drawLine(x, y, x, y);
}
}
The issue is that if I have upwards of a couple hundred units, which will be common, it slows the program down a ton because of nesting a forloop of units in another forloop of units. 问题在于,如果我有超过几百个单位,这将是常见的,它会使程序减慢一吨,因为在另一个单位的环路中嵌入了一个单位的循环。
You can use Area class to combine ellipses (each ellipse represents the Unit shape). 您可以使用Area类来组合椭圆(每个椭圆代表单位形状)。 Eg
例如
Shape s=new Ellipse2D.Float(10,10,200,100);
Area a=new Area(new Ellipse2D.Float(150,20,100,200));
a.add(new Area(s));
Then you can use the sum Area as outline. 然后您可以使用和面积作为轮廓。 See working example here
请参阅此处的工作示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.