Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a CGPoint is inside a UIImageView?

Tags:

iphone

In touchesBegan:

CGPoint touch_point = [[touches anyObject] locationInView:self.view];

There are tens of UIImageView around, stored in a NSMutableArray images. I'd like to know is there a built-in function to check if a CGPoint (touch_point) is inside one of the images, e.g.:

for (UIImageView *image in images) {
   // how to test if touch_point is tapped on a image?
}

Thanks

Follow up:

For unknown reason, pointInside never returns true. Here is the full code.

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
    { 
      UITouch *touch = [touches anyObject]; 
        touch_point = [touch locationInView:self.view];
        for (UIImageView *image in piece_images) {
            if ([image pointInside:touch_point withEvent:event]) {
                image.hidden = YES;
            } else {
                image.hidden = NO;
            }
            NSLog(@"image %.0f %.0f touch %.0f %.0f", image.center.x, image.center.y, touch_point.x, touch_point.y);
        }
    } 

although I can see the two points are sometimes identical in the NSLog output.

I also tried:

  if ([image pointInside:touch_point withEvent:nil]) 

the result is the same. never returns a true.

To eliminate the chance of anything goes with with the images. I tried the following:

  if (YES or [image pointInside:touch_point withEvent:event])

all images are hidden after the first click on screen.

EDIT 2:

Really weird. Even I hard coded this:

        point.x = image.center.x;
        point.y = image.center.y;

the code becomes:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
    { 
        UITouch *touch = [touches anyObject]; 
        CGPoint point; // = [touch locationInView:self.view];
        for (UIImageView *image in piece_images) {
            point.x = image.center.x;
            point.y = image.center.y;       
            if ([image pointInside:point withEvent:event]) {
                image.hidden = YES;
                NSLog(@"YES");
            } else {
                image.hidden = NO;
                NSLog(@"NO");
            }
            NSLog(@"image %.0f %.0f touch %.0f %.0f", image.center.x, image.center.y, point.x, point.y);
        }
    }

pointInside always returns false ...

like image 569
ohho Avatar asked Dec 17 '22 00:12

ohho


1 Answers

Sounds to me like the problem is you need to convert coordinates from your view's coordinates to the UIImageView's coordinates. You can use UIView's convertPoint method.

Try replacing

if ([image pointInside:touch_point withEvent:event]) {

with

if ([image pointInside: [self.view convertPoint:touch_point toView: image] withEvent:event]) {

(Note that you are allowed to pass nil instead of event.)

I guess this is a bit late for the questioner, but I hope it is of use to someone.

like image 147
Emil Avatar answered Jan 09 '23 04:01

Emil