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

…衆ロ難τιáo~ 提交于 2019-12-05 01:47:01

问题


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?


回答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;
}



回答2:


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)
    }
}



回答3:


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);



回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/19721328/objective-c-generating-a-random-point-which-lies-in-given-cgrect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!