如何计算不接触UIView的随机CGPoint [英] How to calculate a random CGPoint which does not touch a UIView

查看:69
本文介绍了如何计算不接触UIView的随机CGPoint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例视图:

我想用CGPoint计算帧,在这里我可以生成另一张卡(UIView)而无需接触任何现有卡.当然,它是可选的,因为视图可以充满卡片,因此没有空闲点.

I want to calculate a frame with a CGPoint where I can spawn another card(UIView) without touching any existing card. Ofcourse it is optional since the view can be full of cards, therefore there is no free spot.

这是我在屏幕上看到任何卡片的方式,现在是这样:

This is how I can see any card on the screen and my function how it is now:

func freeSpotCalculator() -> CGPoint?{
    var takenSpots = [CGPoint]()
    for card in playableCards{
        takenSpots.append(card.center)
    }

}

我不知道从哪里开始以及如何计算屏幕上的随机CGPoint.随机帧的widthheight与屏幕上的卡片相同.

I have no idea where to start and how to calculate a random CGPoint on the screen. The random frame has the same width and height as a card in on the screen.

推荐答案

幼稚的方法很简单,但是一旦屏幕填满,可能会出现问题.生成一个随机CGPoint,其x坐标在0和屏幕宽度之间,而y坐标在0和屏幕高度之间.检查以该点为中心的矩形是否与任何现有视图相交.如果没有,则您的位置是随机的.

The naive approach to this is very simple, but could be problematic once the screen fills up. Generate a random CGPoint with x coordinate between 0 and the screen width and a y coordinate between 0 and the screen height. Check if a rectangle with a center at that point intersects any existing view. If it does not, you have your random position.

出现问题的地方是屏幕开始填满的时间.那时,您可能会尝试许多随机点,然后再找到放置卡的位置.您也可能会遇到无法容纳更多卡的情况.您怎么知道您已经达到目标?生成随机点的循环会永远运行吗?

Where this gets problematic is when the screen starts to fill up. At that point you could be trying many many random points before finding a place to put the card. You could also reach a situation where no more cards will fit. How do you know that you have reached that? Will your loop generating the random points just run forever?

一个更聪明的解决方案是跟踪屏幕上的可用空间.始终在这些可用空间内大致生成随机点.如果近似值足够接近,则可以使用网格来执行此操作.是否有一张卡占据每个网格位置?然后,当最大可用空间小于卡片矩形的大小时,您就知道完成了.比天真的方法要花很多时间,但是当屏幕开始充满时它会更快,并且您会确定何时完成操作.

A smarter solution is to keep track of the free spaces on the screen. Always generate your random points roughly within these free spaces. You could do this using a grid if approximate is close enough. Is there a card occupying each grid location? Then when the largest free space is smaller than the size of your card rectangle, you know you're done. It's a lot more work than the naive approach, but it's faster when the screen starts to fill up and you'll know for sure when you're done.

如果您知道自己的屏幕空间将永远超过卡片可能会占用的空间,那么幼稚的方法就可以了.

If you know that you will always have more screen space than the cards can possibly take up, the naive approach is fine.

这篇关于如何计算不接触UIView的随机CGPoint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆