问题描述
我想在固定大小的父级中放置任意数量的矩形,以使它们为:
I'd like to place an arbitrary number of rectangles into a fixed size parent such that they are:
- 随意放置
- 随机旋转到给定程度范围内
- 很好地分散在中心点周围(不是全部都聚集在一个角上)
- 由于空间不足,除非有必要,否则不要重叠
- 必要时尽量减少重叠
为帮助您可视化问题,我想将图像分散在窗口中,以供用户选择.
To help you visualize the problem, I would like to scatter images inside a window for the user to choose one.
Google搜索使我做了各种打包等算法,但没有什么能真正满足我的要求.
Googling had led me do various algorithms for packing etc, but nothing really addresses my requirements.
有人有什么好主意吗?
推荐答案
它应该比以下复杂得多:
It shouldn't be much more complicated than:
- 将新矩形随机旋转放置在随机位置.只需使用三个随机值(x,y,r)即可,除非您还需要随机大小(在这种情况下,您也需要w和h).这不应该使任何一个角落结块(通过随机是随机的).
- 对于每个已放置的矩形,检查是否有碰撞. 这里是一种方式.不想让事物延伸到屏幕之外);在边框周围放置四个虚拟矩形可能是一种便宜的方法.
- 如果发生任何碰撞,则有两种选择:将新矩形移动到新的随机位置,或者将新矩形和阻塞矩形彼此远离,直到不再接触为止.两者都可以-仅仅移动新页面会更快,更轻松,尽管如果页面真的很满,可能永远找不到合适的位置.几乎肯定会成功移动它们,但是花费更长的时间,并且可能导致连锁反应冲突,所有这些冲突都必须递归解决.
无论如何,您都想尽量减少矩形的数量,因为比较的数量会很快变大.使用短路(例如如果它们在屏幕的中间,那么就不要打扰它们")可能会有所帮助,但不能保证.
In any case you'll want to try and keep the number of rectangles small, because the number of comparisions can quickly get really big. Using a short-circuit (such as "if they're halfway across the screen then don't bother looking closely") may help but isn't guarenteed.
好的,所以要求#5.很有可能,推入两个矩形直到它们不再被递归地添加新的矩形的方法最终将成为最简单的方法-在几千次迭代后切断循环,一切都会试图尽可能远离其他任何东西,从而使重叠最小.或者,让该方法在单独的线程中运行,以便用户可以看到它们随着添加的更多内容而扩展开(也可以阻止它看起来像在思考时被锁定),一旦没有一个矩形在一个单元中移动超过X个单位就停止迭代.
Okay, so requirement #5. Chances are that the push-both-rectangles-until-they-no-longer-collide-recursively method of adding new rectangles will end up being the simplest way to do this - just cut off the loop after a few thousand iterations and everything will have attempted to move as far away from everything else as possible, leaving minimum overlap. Or, leave the method running in a seperate thread so that the user can see them spreading out as more are added (also stopping it from looking like it's locking up while it's thinking), stopping once no rectangle has moved more than X units in one iteration.
这篇关于如何以最小的重叠和良好的分散性随机放置矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!