Search code examples
iphoneuiimageviewuiimagetouchesbeganuser-interaction

UIImageView pixel-perfect `touches began` for non-transparent parts of UIImage


developing iphone app, I have used a UIImageview and i have set an image of irregular shape

// uiimageview type shutter
shutter = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,32.5)];

//setting image on shutter
UIImage* shutterimg = [UIImage imageNamed:@"trayshutter.png"];
[shutter setImage:shutterimg];
// User interaction
shutter.userInteractionEnabled=YES;

and i get touches using touchesbegan

everything is fine, but issue is I also get events in all the rectangle area occupied by the CGRectMake (i.e. 0,0,320,32.5) of imageview, whereas i require events only on the image (which is of shape of -----|||||-----).

How can i make sure that i get events only on the image and not on the rest of area covered by cgrectmake ?


Solution

  • - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
      UITouch *touch = [touches anyObject];
      if ([touch view] == yourDesiredImage) {
        // Do something here
      }
    }
    

    EDIT: maybe you can try UITapGestureRecognizer instead:

    UITapGestureRecognizer * tapGestureRecognizer = [[UITapGestureRecognizer alloc] init];
    [tapGestureRecognizer addTarget:self action:@selector(yourTouchMethod:)];
    [tapGestureRecognizer setNumberOfTapsRequired:1];
    [shutter addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];