Hit Detection for Zoomed UIScrollViews

A reader writes (in reference to CATiledLayer Part 2):

I have a simple pdf that has a couple of graphics on it. For example a circle and a square. This pdf is within a UIView that “has-a” CATiledLayer like yours. If the circles center is at (100,100), I want to be able to “touch” the center of the circle and get back (100, 100) no matter what the zoom is. …

I have a UIGestureRecognizer and intercept a single tap and then look at the locationInView:. I have yet to figure out what to do to get back these coordinates.


Later, he wrote that he had solved his problem:

[E]ach UIView has a method called convertPoint:fromView: and convertPoint:toView: (from the View Programming Guide for iOS).
Amazing what happens when you read the docs closely!

So, if one makes sure to figure out the initial scale factors for the pdf or png used, you can determine exactly where (as in (x,y) location) the hit is regardless of a UIScrollView scale factor. In fact, the methods above ignore any zoom scale factors if your png is in a UIScrollView.


I had some difficulty trying to help solve this problem, for a somewhat interesting reason: I’d fumbled the re-creation of the problem in such a way that the problem didn’t exist. I was generating the correct numbers directly from locationInView:, so, naturally, all my attempts to manipulate them produced wrong answers.

I had attached my UIGestureRecognizer to the content view inside the UIScrollView, while the reader had (I believe) attached his to the UIScrollView itself.

So, I think an alternate solution to the stated problem is to simply attach the UIGestureRecognizer to the inner view. You can see an example of this here; the demo logs the world-space location of any tap to the console.

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • Reddit
  • HackerNews
  • del.icio.us
  • Google Bookmarks
  • Slashdot
This entry was posted in iPhone. Bookmark the permalink.

Comments are closed.