Java: drawing nonoverlapping shapes randomly within area
I need to draw some graphics objects on a JPanel in a JApplet, they are Graphics2D objects.
Here is some visual help
1) I would like to draw circles near the boundaries of the panel at random coordinates so that every time the applet is started it looks different. I would like in some way to say that exclude this part, don't draw there - blue circle in image.
2) Would be nice if I could evenly distribute them so that if there are 4 circles, then the distance between the circles is almost the same, but still random to some amount.
3) If the first 3 or 4 circles are drawn then draw the other smaller and random sized circles are drawn all over the panel that isn't used.
It seems like a strange idea but would it be possible to make an algorithm that gives you the centre coordinates based on some constraints like (x-100)^2 + (y-100)^2 >200 && 0< x <400 && 0< y < 400
No开发者_如何学Gow I do it like this: divide the whole area into a grid where every slot in the gird is free or taken and inside that slot draw the circles at random coordinates, but still within that slot.
That idea doesn't look so good and I would like to do it better. I'm implementing this in java but general ideas are also welcome.
If you have only circles, the "not overlapping" test is easy: Two circles are not overlapping if and only if the distance of there centers is bigger than the sum of their radiuses (for equality they are touching). For overlapping the border: the distance from the border must be bigger than the radius.
So, you could simply go on and generate random coordinates (either with fixed or random radiuses), then check if any are overlapping. If yes, either start again, or throw away only the overlapping ones and go on.
If you have not too many circles, this simple algorithm is enough. If it starts taking too long, you might think about using some spatial data structure, so you will only have to check the circles near to your new point.
You may want to create the list of circles to paint not inside of the paintComponent method, but instead in the init()
or start()
method (or some thread called from there), so the painting will not take too long, and the circles will not change for every (maybe even partial) repaint.
精彩评论