i'm trying to randomly generate images that look similar to identity cards. I already generate different things like name, address and birth date but i don't want them to overlap.
I tried something like this:
public int[] getUnusedPos(int w, int h) {
if(boxes.size()==0) {
int x = rand.nextInt(screenWidth-w);
int y = rand.nextInt(screenHeight-h)+h;
return new int[] {x,y};
}
int x =0;
int y = 0;
boolean xFound = false;
boolean yFound = false;
while(!xFound||!yFound) {
x = rand.nextInt(screenWidth+1-w);
xFound=true;
y = rand.nextInt(screenHeight-h)+h;
yFound = true;
for(Box b : boxes) {
if(x>b.getX()-w&&x<b.getX()+b.getW()) {
xFound = false;
}
if(y>b.getY()+h&&y<b.getY()-b.getH()) {
yFound = false;
}
}
}
return new int[] {x,y};
}
w and h are width and height of the box that should be drawn next. boxes is a list that contains the positions of all the drawn boxes before. I then randomly generate x and y coordinates and check if the new box would fit in the screen without overlapping with a different box.
For the first 2-3 boxes this works, but i need to draw 6 and it takes forever to find x and y values. I know there is a way to generate random ints in ranges, but i dont know how to define these ranges from the boxes i already drew.
Any ideas?
Aucun commentaire:
Enregistrer un commentaire