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

5

5

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?

Meaghan answered 1/11, 2013 at 5:29 Comment(0)
G
10
- (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;
}
Genetic answered 1/11, 2013 at 10:57 Comment(1)
+ 1, but you should use arc4random_uniform(u_int32_t upper_bound). Reason as per doc: "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." ;)Footcloth
L
5

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)
    }
}
Luvenialuwana answered 11/6, 2016 at 6:7 Comment(0)
M
0

First, check out this post for generating random numbers: Generating random numbers in Objective-C

Then use CGPointMake(x,y) to create your point using random numbers:

int x = RandomNumberGenerator1Output;
int y = RandomNumberGenerator2Output;

CGPoint myPoint = CGpointMake(x, y);
Moncear answered 1/11, 2013 at 5:34 Comment(0)
S
0

Same as any random number generator. You need two random numbers, x and y. Just generate x between 0 and rect.size.width and y between 0 and rect.size.height

Add rect.origin.x or rect.origin.y respectively. Random number generation is well covered elsewhere. Look for the arc4random family of functions.

Swanky answered 1/11, 2013 at 5:38 Comment(0)
R
0

To generate a random point in a rectangle to need to generate random X and Y between Start and End coordinates of your rectangle.

if RECT is your rectangle then -

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

If you want to know how to generate a random number between two numbers then you can go here - Generate Random Numbers Between Two Numbers in Objective-C

Rawhide answered 1/11, 2013 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.