Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Point inside a rotated CGRect

How would you properly determine if a point is inside a rotated CGRect/frame?

The frame is rotated with Core Graphics.

So far I've found an algorithm that calculates if a point is inside a triangle, but that's not quite what I need.

The frame being rotated is a regular UIView with a few subviews.

like image 247
Dids Avatar asked Jun 08 '13 18:06

Dids


2 Answers

Let's imagine that you use transform property to rotate a view:

self.sampleView.transform = CGAffineTransformMakeRotation(M_PI_2 / 3.0);

If you then have a gesture recognizer, for example, you can see if the user tapped in that location using locationInView with the rotated view, and it automatically factors in the rotation for you:

- (void)handleTap:(UITapGestureRecognizer *)gesture
{
    CGPoint location = [gesture locationInView:self.sampleView];

    if (CGRectContainsPoint(self.sampleView.bounds, location))
        NSLog(@"Yes");
    else
        NSLog(@"No");
}

Or you can use convertPoint:

- (void)handleTap:(UITapGestureRecognizer *)gesture
{
    CGPoint locationInMainView = [gesture locationInView:self.view];

    CGPoint locationInSampleView = [self.sampleView convertPoint:locationInMainView fromView:self.view];

    if (CGRectContainsPoint(self.sampleView.bounds, locationInSampleView))
        NSLog(@"Yes");
    else
        NSLog(@"No");
}

The convertPoint method obviously doesn't need to be used in a gesture recognizer, but rather it can be used in any context. But hopefully this illustrates the technique.

like image 82
Rob Avatar answered Nov 16 '22 14:11

Rob


Use CGRectContainsPoint() to check whether a point is inside a rectangle or not.

like image 20
Roshan Avatar answered Nov 16 '22 14:11

Roshan