Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Point not in Rect but CGRectContainsPoint says yes

If I have a UIImageView and want to know if a user has tapped the image. In touchesBegan, I do the following but always end up in the first conditional. The window is in portrait mode and the image is at the bottom. I can tap in the upper right of the window and still go into the first condition, which seems very incorrect.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:touch.view];

if(CGRectContainsPoint(myimage.frame, location) == 0){
//always end up here
}
else
{ //user didn't tap inside image}

and the values are:

location: x=303,y=102
frame: origin=(x=210,y=394) size=(width=90, height=15)

Any suggestions?

like image 394
4thSpace Avatar asked Nov 29 '22 20:11

4thSpace


2 Answers

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 location = [touch locationInView:self]; // or possibly myimage instead of self.

Next, CGRectContainsPoint returns a boolean, so comparing it to 0 is very odd. It should be:

if ( CGRectContainsPoint( myimage.frame, location ) ) {
   // inside
} else {
   // outside
}

But if self is not myimage then the myimage view may be getting the touch instead of you - its not clear from your question what object self is it is is not a subclass of the UIImageView in question.

like image 110
Peter N Lewis Avatar answered Dec 01 '22 09:12

Peter N Lewis


Your logic is simply inverted. The CGRectContainsPoint() method returns bool, i.e. true for "yes". True is not equal to 0.

like image 27
unwind Avatar answered Dec 01 '22 10:12

unwind