How to limit iPhone tap gesture recognition to inside a circular image?

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

I'm trying to place a circular image on an iPhone view and then consume taps inside the circle but not outside of it. The problem I'm running into is that when I place a UIImageView on the screen view in Interface Builder, I seem to be constrained to a rectangular shape. I tried using an image of a circle with the area outside the circle left as transparent but the image in total is still rectangular, so when it's placed on a UIImageView and hooked up to recognize tap gestures it still picks up the taps outside the circle itself.

The image below shows what I mean. The blue dots represent the outer border of the UIImageView that holds the image. The tap gesture recognition is currently linked to that UIImageView but as you can see, there is a bit of space at the corners of the UIImageView that are not covered by the circular image. Is there any way to either conform a UIImageView to a non-rectangular shape or to place an image on a View without using a UIImageView and still be able to hook up tap recognition?

image of walter with transparent background on a UIImageView http://img237.imageshack.us/img237/2164/walterheadshot.png

I'm pretty new to iPhone graphics but does anyone have some ideas on this or can point me in the right direction?

Thanks!

回答1:

Assumes a circle, and not just an oval:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {     CGFloat halfSize = [self bounds].size.width * 0.5f;     CGPoint location = [[touches anyObject] locationInView:self];     location.x -= halfSize;     location.y -= halfSize;     CGFloat squaredDistanceFromCenter = location.x * location.x + location.y + location.y;     if (squaredDistanceFromCenter < (halfSize * halfSize)) {         NSLog(@"Within circle :)");     } else {         NSLog(@"Not within circle :(");     } }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!