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?
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?
- (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;
}
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)
}
}
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);
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.
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
© 2022 - 2024 — McMap. All rights reserved.
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