5

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.

lnafziger
  • 25,760
  • 8
  • 60
  • 101
Dids
  • 569
  • 7
  • 24

2 Answers2

14

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.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Thank you very, very much. This works like a charm, just didn't know that iOS/UIKit handles the conversion pretty much by itself. Thanks again! – Dids Aug 19 '13 at 20:07
1

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

Roshan
  • 1,937
  • 1
  • 13
  • 25
  • This doesn't take rotation into account. Rectangles are always parallel to the x and y axes; if you have a rectangular shape that is rotated or skewed (e.g., in a vector-graphics app), you need to accurately test whether the touch is within the rotated shape, even if the model object only has a rectangle. – Peter Hosey Jun 09 '13 at 01:15