Objective-C生成一个随机点,它位于给定的cgrect中

hai*_*ham 4 random cocoa-touch ios cgrect

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

我该如何处理这种情况?

Luk*_*kas 9

- (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;
}
Run Code Online (Sandbox Code Playgroud)

  • + 1,但你应该使用[`arc4random_uniform(u_int32_t upper_bound)`](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/arc4random_uniform.3.html).根据doc的原因:`"arc4random_uniform()建议使用像``arc4random()%upper_bound''这样的结构,因为当上限不是2的幂时,它避免了"模偏差"."`;) (5认同)

Ish*_*nda 5

原始问题专门针对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)
    }
}
Run Code Online (Sandbox Code Playgroud)