简体   繁体   English

如何均匀分散点而不相互重叠?

[英]How can I evenly scatter points without overlapping each other?

I'd like to evenly scatter stars to represent a night sky background in a UIView, based on the UIView's width and height. 我想基于UIView的宽度和高度,均匀地散射星星来代表UIView中的夜空背景。 Each star must be at least 20 pixels apart. 每颗恒星必须至少相隔20个像素。

I tried the following to generate the X and Y points, but it is highly inefficient and ends up freezing the app because too often the randomly generated numbers are too similar to those in the existing array, causing it to loop again infinitely. 我尝试了以下方法来生成X和Y点,但效率非常低并最终冻结了应用程序,因为随机生成的数字太频繁地与现有数组中的数字太相似,导致它无限循环。

func generateRandomNumber(maxValue: UInt32, uniquePoints: Set<Int>) -> Int {
    let randomNumber = Int(arc4random_uniform(maxValue))

    for point in uniquePoints {
        if(abs(randomNumber - point) < 20) {
            return generateRandomNumber(maxValue, uniquePoints)
        }
    }

    return randomNumber
}

Is there a more efficient way to do this? 有没有更有效的方法来做到这一点?

The easiest way, if they need to be 20 pixels apart is to divide your area into 20 x 20 squares. 最简单的方法是,如果它们需要相隔20个像素,则将您的区域划分为20 x 20格。 Randomly place 1 star in each 20 x 20 cell, but skip every other column and row. 在每个20 x 20单元格中随机放置1颗星,但跳过每隔一列和每行。 So it would look like this: 所以它看起来像这样:

*-*-*-*-*
|-|-|-|-|
*-*-*-*-*
|-|-|-|-|

etc. In the above illustration, cells with a * in them would have a single star. 在上图中,其中带有*单元格将具有单个星形。 Cells with either a - or a | 与无论是细胞-还是| would be empty. 会是空的。

If you want to get more complicated, you can look up Poisson Disc . 如果你想变得更复杂,你可以查找Poisson Disc This is a more complicated method that achieves what you want more elegantly. 这是一种更复杂的方法,可以更优雅地实现您想要的效果。 It's a little harder to understand, though, and can often be computationally intensive. 但是,它有点难以理解,并且通常可能是计算密集型的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Swift中将两个元素(不知道其宽度)彼此居中? - how can I center two elements (without knowing their width) next to each other in Swift? Xcode中的UI元素似乎相互重叠。 如何解决这个问题? - UI elements in Xcode seem to be overlapping with each other. How to fix this? 如何防止出队的集合视图单元格彼此重叠? - How to prevent dequeued collection view cells from overlapping each other? 如何将UILabel放置在UIImageView下方,以使其始终均匀放置 - How can I place a UILabel below an UIImageView such that it is always evenly placed 如何动态制作UILabel而不与其他UILabel重叠 - how to make UILabel dynamically without overlapping with other UILabel 如何让我的 iOS 应用程序相互通信? - How can I make my iOS apps talk to each other? ViewController在Main.Storyboard中彼此重叠 - ViewControllers overlapping each other in Main.Storyboard CorePlot:如何滚动到散点图的行尾? - CorePlot: How can I scroll to the end of the line of a scatter plot graph? iOS:如何在不互相干扰的情况下执行块? - iOS: How do I get my blocks to execute without interrupting each other? 如何使用情节提要约束均匀地并排放置两个UIPickerView? - How can I evenly space two UIPickerView side by side using storyboard constraints?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM