0

如何获得屏幕边界(帧)之外的随机 CGPoint?

另外,考虑到这一点,我怎么能在屏幕中间找到一个对称的点——例如说我有这个点(宽度+1,高度+1)。现在对称点是 (-1,-1)。假设我有(-1,高度+1)-对称将是(宽度+1,-1)。

希望这很清楚,谢谢!

4

2 回答 2

1

If I understand your question correctly, you can use the following method:

- (CGPoint) randomPointIn:(CGRect)inrect outsideOf:(CGRect)outrect
{
    CGPoint p;
    do {
        p.x = inrect.origin.x + inrect.size.width * (float)arc4random()/(float)UINT32_MAX;
        p.y = inrect.origin.y + inrect.size.height * (float)arc4random()/(float)UINT32_MAX;
    } while (CGRectContainsPoint(outrect, p));
    return p;
}

It returns a random point that is inside inrect, but outside of outrect. (I have assumed that inrect is "considerably larger" than outrect, otherwise many loop iterations might be necessary to find a valid point.)

In your case, you would use outrect = CGRectMake(0, 0, width, height), and inrect would specify the allowed domain.

And the point symmetrical to (x, y) with respect to the middle of the screen with size (width, height) is (width - x, height - y).

UPDATE: As I just found here: http://openradar.appspot.com/7684419, CGRectContainsPoint will return false if you provide it a point that is on the boundary of the CGRect. That means that the above method returns a point that is outside of or on the boundary of the given rectangle outrect. If that is not desired, additional checks can be added.

于 2013-08-04T11:55:57.663 回答
-1

我相信这应该有效。

//To get a random point
- (CGPoint)randomPointOutside:(CGRect)rect
{
    // arc4random()%(int)rect.size.width
    // This gets a random number within the width of the rectangle
    //
    // (arc4random()%2) ? rect.size.width : 0)
    // This has a 50:50 to put the point in the q1 quadrant relative to the top right point of the rect
    //
    //    q4       q1
    //   _____ +  
    //  |     |
    //  | q3  |    q2
    //  |_____|
    //
    float x = arc4random()%(int)rect.size.width + ((arc4random()%2) ? rect.size.width : 0);
    float y = arc4random()%(int)rect.size.height + ((arc4random()%2) ? rect.size.height : 0);
    return CGPointMake(x, y);
}

//To get the symmetrical point
- (CGPoint)symmetricalPoint:(CGPoint)p around:(CGRect)rect
{
    return CGPointMake((p.x-rect.size.width) * -1, (p.y-rect.size.height) * -1);
}
于 2013-08-04T12:42:26.510 回答