所以我必须在每个正方形内部随机x和y坐标绘制4个正方形然后10个随机正方形,它们必须是对称的,然后并排绘制整个屏幕。每个部分(4个大正方形是一个部分)必须具有相同的随机正方形并且颜色相同。我已经达到了可以绘制单个部分但我无法想到任何东西使它们被反复绘制的程度,因此它们用相同的随机方块和随机颜色覆盖整个屏幕。希望你理解它。这就是我现在所拥有的。
@Override
public void paint(Graphics g){
int a=100;
Random rand = new Random();
g.setColor(Color.black);
g.drawRect(50, 50, a, a);
g.drawRect(50+a, 50, a, a);
g.drawRect(50, 50+a, a, a);
g.drawRect(50+a, 50+a, a, a);
int r = rand.nextInt(a/2);
int rx = rand.nextInt(a/2)+50;
int ry = rand.nextInt(a/2)+50;
int rxsim = (2*a+50)-(rx-50)-r;
int rysim = (2*a+50)-(ry-50)-r;
g.setColor(new Color(rand.nextInt(255),rand.nextInt(255),rand.nextInt(255)));
g.fillRect(rx, ry, r, r);
g.fillRect(rxsim, ry, r, r);
g.fillRect(rx, rysim, r, r);
g.fillRect(rxsim, rysim, r, r);
}
答案 0 :(得分:0)
您可以测量屏幕尺寸(或框架,等等)和矩形尺寸
int widthScreen = getWidth();//TODO implement this
int widthSample = getSampleWidth();//TODO implement that (looks like 50 in your code)
一旦你知道你计算的尺寸:
int amountHorizontal = widthScreen / widthSample + 1; //adding one extra
当然你也必须对amountVertical做同样的事情,这是相同的技术......
然后你画它dx / dy次
Graphics g; //your graphics to draw on
Rectangle r; //a rectanlge to be drawn
for(int dy = 0; dy < amountHorizontal; dy++){
for(int dx = 0; dx < amountHorizontal; dx++){
if(dx%2 == 0 && dy%2 == 0){ //even & even
drawUpperLeft(r, dx, dy, g)
}
if(dx%2 != 0 && dy%2 == 0){ //odd & even
drawUpperRight(r, dx, dy)
}
if(dx%2 == 0 && dy%2 != 0){ //even & odd
drawLowerLeft(r, dx, dy)
}
if(dx%2 != 0 && dy%2 != 0){ //odd & odd
drawLowerRight(r, dx, dy)
}
}
}
这是一个如何实现一个绘制方法的例子:
private void drawLowerRight(Rectangle r, int xOff, int yOff, Graphics g){
//you already know how to rotate a rectangle by 90/180/270 degree
Rectangle rot = createRectanlge(r, 270);
int x = xOff * widthSample;
int y = yOff * widthSample;
rot.x = rot.x + xOff;
rot.y = rot.y + yOff;
g.drawRect(rot);
}