Where Was Touch – Determine if Touch/Point is Within Rectangle

I recently had to write a short chunk of code to determine when a user touches a specific rectangular region on the screen. Detecting this is nothing more than getting a reference to a CGPoint (x and y coordinates) of the location touched and checking to see if the point is within the rectangular bounds of interest.

The following example shows one approach, the workhorse is CGRectContainsPoint.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*---------------------------------------------------------------------------
* Touches began
*--------------------------------------------------------------------------*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
  // Detect touch anywhere
  UITouch *touch = [touches anyObject];
 
  // Get the specific point that was touched
  CGPoint point = [touch locationInView:self.view]; 
  NSLog(@"pointx: %f pointy:%f", point.x, point.y);
 
  // See if the point touched is within these rectangular bounds
  if (CGRectContainsPoint(CGRectMake(5, 5, 40, 130), point))
  {
    do something...
  } 
}

I use CGRectMake to define the bounds of the rectangle and pass in the variable point that was obtained from the touch location.

As with CGRectContainsPoint, CGRectMake is a C function, which is defined as follows:

CGRect CGRectMake(CGFloat x, CGFloat y, CGFloat width, GFloat height);

The C structures you’ll need to put all the pieces together, are shown below:

struct CGRect 
{
   CGPoint origin;
   CGSize size;
};
 
struct CGPoint 
{
   CGFloat x;
   CGFloat y;
};
 
struct CGSize 
{
   CGFloat width;
   CGFloat height;
};

CGFloat is nothing more than a floating point number that is defined as a typedef, based on the system architecture. In other words, it’s just a float.

For more information about CGRect, CGSize and CGPoint, you can read this post.

  1. Thank you very much for this. I was capturing tap events on my view and this would obviously block my UIButton touches, so this came in very handy passing the events along to their respective UI piece.

  2. Great snippet. Also helpful for restricting the range of movement of a dragged view. Thanks!

Comments are closed.