Search code examples
xcodeuiimageviewsensorsuitouchproximity

How to check touch proximity to an UIImageView?


Does anyone know how I would check the touch proximity to an UIImageView in Xcode? I am trying to check if the touch is within 25 pixels of an UIImageView which moves around the screen. Any help would be appreciated. Thank you.


Solution

  • First, you get the touch with:

    UITouch *touch = [[event allTouches] anyObject];
    

    Next, you want to be checking for the locationInView relative to your image view.

    CGPoint touchlocation = [touch locationInView:self]; // or possibly myimage instead of self.
    

    Next, CGRectContainsPoint returns a boolean. It should be:

    if ( CGRectContainsPoint( imgView.frame, touchlocation ) ) {
       // inside imgView
    } else {
       // outside imgView Now we will found out is it within proximityImgViewRect
       CGRect *proximityImgViewRect = CGRectMake( imgView.frame.origin.x-25,imgView.frame.origin.y - 25, imgView.frame.size.width+50,imgView.frame.size.height+50); 
       if ( CGRectContainsPoint( proximityImgViewRect.frame, touchlocation ) ) {
         // inside proximityImgViewRect
       } else {
        //outside proximityImgViewRect
       }
    }