【问题标题】:Objective-C generating a random point which lies in given cgrectObjective-C 生成一个位于给定 cgrect 中的随机点
【发布时间】:2013-11-01 05:29:04
【问题描述】:

我的要求是在给定区域生成一个随机点,即我有一个空间的 Cg 矩形,我需要在这个矩形中生成一个随机点..

在这种情况下我该如何进行?

【问题讨论】:

    标签: ios cocoa-touch random cgrect


    【解决方案1】:
    - (CGPoint)randomPointInRect:(CGRect)r
    {
        CGPoint p = r.origin;
    
        p.x += arc4random_uniform((u_int32_t) CGRectGetWidth(r));
        p.y += arc4random_uniform((u_int32_t) CGRectGetHeight(r));
    
        return p;
    }
    

    【讨论】:

    • + 1,但您应该使用arc4random_uniform(u_int32_t upper_bound)。根据文档的原因:"arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two." ;)
    【解决方案2】:

    最初的问题专门针对 Objective-C,但 Swift 解决方案可能会对某人有所帮助。

    extension CGRect {
        func randomPointInRect() -> CGPoint {
            let origin = self.origin
            return CGPointMake(CGFloat(arc4random_uniform(UInt32(self.width))) + origin.x, CGFloat(arc4random_uniform(UInt32(self.height))) + origin.y)
        }
    }
    

    【讨论】:

      【解决方案3】:

      首先,查看这篇关于生成随机数的帖子:Generating random numbers in Objective-C

      然后使用 CGPointMake(x,y) 使用随机数创建您的点:

      int x = RandomNumberGenerator1Output;
      int y = RandomNumberGenerator2Output;
      
      CGPoint myPoint = CGpointMake(x, y);
      

      【讨论】:

        【解决方案4】:

        与任何随机数生成器相同。 你需要两个随机数,x 和 y。 只需生成 0 和 rect.size.width 之间的 x 和 0 和 rect.size.height 之间的 y

        分别添加 rect.origin.x 或 rect.origin.y。 随机数生成在其他地方得到了很好的介绍。 寻找 arc4random 函数族。

        【讨论】:

          【解决方案5】:

          要在矩形中生成随机点,需要在矩形的起始坐标和结束坐标之间生成随机 X 和 Y。

          如果 RECT 是你的矩形,那么 -

          X = Random (RECT-Origion-X,RECT-Size-Width)
          Y = Random (RECT-Origion-y,RECT-Size-Height)
          

          如果你想知道如何在两个数字之间生成一个随机数,那么你可以去这里 - Generate Random Numbers Between Two Numbers in Objective-C

          【讨论】:

            猜你喜欢
            • 2018-04-03
            • 2011-09-18
            • 1970-01-01
            • 2023-03-11
            • 2012-04-22
            • 1970-01-01
            • 1970-01-01
            • 2023-03-28
            • 1970-01-01
            相关资源
            最近更新 更多