Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C generating a random point which lies in given cgrect

my requirement is generating a random point in a given area, i.e i have an Cg Rectangle of some space and I need to generate a random point in this rectangle ..

how can I proceed in this scenario?

like image 935
gowtham kosaraju Avatar asked Dec 07 '22 04:12

gowtham kosaraju


2 Answers

- (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;
}
like image 66
Quxflux Avatar answered Dec 29 '22 00:12

Quxflux


The original question asks specifically for Objective-C, but a Swift solution might help someone.

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)
    }
}
like image 33
Ishan Handa Avatar answered Dec 28 '22 23:12

Ishan Handa