我創建了5個圓形,使用3個數組(x,y和半徑大小)隨機選擇x和y座標和半徑。但是,我需要圓圈根據是否與另一個圓圈重疊來動態更改顏色。所以如果5個圓圈中的一個完全不重疊,它應該被塗成黑色。重疊的圓應該是青色。如果兩個圓的中心點之間的距離小於它們的半徑之和,則認爲兩個圓重疊。如何檢測重疊的圓形並相應地填充顏色?
這是我迄今爲圈子類寫的。 以下代碼將成功繪製小程序窗口中的5個圓圈,並且距離已成功計算,但問題與着色有關。顏色填充似乎存在邏輯錯誤,我在這裏看不到問題。有什麼建議麼?非常感謝。
public class Circles extends Applet {
public void paint(Graphics page)
{
Random locator = new Random();
int [] xpt = new int [5];
int [] ypt = new int [5];
int [] rad = new int [5];
setPreferredSize (new Dimension(300, 300));
for (int i = 0; i < xpt.length; i++){
xpt[i] = locator.nextInt(100); //need to set a number or it goes into millions, cannot set it in Random()
ypt[i] = locator.nextInt(100);
rad[i] = locator.nextInt(100);
System.out.println("The #" + i + " x-point: " + xpt[i] + " y-point: " + ypt[i] + " radius: " + rad[i]); //for debugging purposes
for (int j = 0; j < xpt.length; j++){
double xpoint1 = xpt[i]+rad[i];
double ypoint1 = ypt[i]+rad[i];
double xpoint2 = xpt[j]+rad[j];
double ypoint2 = ypt[j]+rad[j];
double radius1 = rad[i];
double radius2 = rad[j];
double theDistance = distance(xpoint1,ypoint1,xpoint2,ypoint2);
System.out.println("Comparing " + i + " to " + j); //for debugging and logic checking
if (i==j)
;
else if (theDistance <= (radius1+radius2))
{
page.setColor(Color.cyan);
page.fillOval(xpt[i], ypt[i], rad[i], rad[i]);
//page.fillOval(xpt[j], ypt[j], rad[j], rad[j]);
System.out.println("Overlap occurred. Colored " + i + " and " + j + " cyan.");
System.out.println("Center points: ("+ xpoint1 +", "+ ypoint1 +") and ("+ xpoint2 + ", "+ ypoint2 + ").");
}
else
{
page.setColor(Color.black);
page.fillOval(xpt[i], ypt[i], rad[i], rad[i]);
//page.fillOval(xpt[j], ypt[j], rad[j], rad[j]);
System.out.println("No overlap. Made " + i + " and " + j + " black.");
}
}
}
}
public static double distance(
double x1, double y1, double x2, double y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
}
但是當你使用 '' 'page.fillOval(XPT [I],展翅[I],弧度[I],弧度[1]);' '' 從平在角落的左上角,所以我必須將半徑長度添加到x和y座標以便找到繪製的圓的中心 – sxflynn 2010-11-13 04:47:02
不,您誤解了我。我已經用代碼更新了答案,以便澄清。 – 2010-11-13 05:01:46