5

Possible Duplicate:
Detect if CGPoint within polygon

I have the coordinates of a set of touches from a UIEvent. Is there a way to check if they are contained within a certain shape -- a polygon -- that I can define?

I have experience in Java, and I would use the polygon class and call the contains(int x, int y) method. Is there a similar way to do this in Cocoa Touch?

Community
  • 1
  • 1

3 Answers3

3

If you define your polygon as a CGPath, you can use CGPathContainsPoint()... Can you tell us more about your application concept?

EDIT:

There's also the higher-level UIBezierPath and/or NSBezierPath.. both of those objects have a -containsPoint method.

nielsbot
  • 15,922
  • 4
  • 48
  • 73
  • Thanks. That seems exactly what I'm looking for. I couldn't find this solution for the life of me. – user1941895 Jan 02 '13 at 04:25
  • well, this is using the Core Graphics C API, so it's not at the level of Obj-C or C++... So it wouldn't appear in the Obj-C class documentation. – nielsbot Jan 02 '13 at 04:26
2

Try using CGRectContainsPoint(CGRect rect, CGPoint point)

See here: https://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html

OR

Detect if CGPoint within polygon

Community
  • 1
  • 1
EXC_BAD_ACCESS
  • 346
  • 1
  • 4
  • 19
0

Maybe you're doing something unusual, like you only want touches to be detected within a triangle or something. If so, you can ignore this. But since you're new to iOS, I would recommend using either a UIControl subclass with target-action pairs or a UIGestureRecognizer.

Example code would be:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

Later in the target -- probably your view controller, you would implement the method:

- (void)buttonPressed:(id)sender
{
}

With a gesture recognizer, you would add the gesture recognizer to a UIView and, like with the UIControl, add a target-action pair:

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
[self.view addGestureRecognizer:tapRecognizer];

- (void)viewTapped:(UIGestureRecognizer *)recognizer
{
}

These are the typical approaches for basic user interaction. You'll have much simpler time with these than using touchesBegan & company, though if they are what you need then the other answerers have you covered.

MaxGabriel
  • 7,617
  • 4
  • 35
  • 82