Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling to a rect when UIScrollView is zoomed?

I have an UIImageView with an image (map) inside of a UIScrollView. I add another image (marker) to the image view (so a map background and a marker). If the marker isn't shown on the screen, when I place the marker I want to scroll to show the marker.

I'm using [scrollView scrollRectToVisible:rect animated:YES] after I place the marker on the map. This works great when the scrollview isn't zoomed. How do I adjust rect based on the zoom scale so the marker is centered in the view?

like image 772
jmosesman Avatar asked Jun 22 '11 21:06

jmosesman


1 Answers

I do something very similar in the app I am currently working on, but instead of using -scrollRectToVisible, I use -setContentOffset.

Because I know where my marker is in the frame, I can easily calculate its center, which I save as the CGFloats centerX and centerY. I then use the following code to center the marker on the screen (I subtract 161 from the Y value because my main view has a tab bar and a navigation controller, so it is not the full 480 points):

CGFloat curZoom = scrollView.zoomScale;

[scrollView setContentOffset:CGPointMake((centerX*curZoom)-160, (centerY*curZoom)-161) animated:NO];

By multiplying the center point by the current zoomScale, I can find the correct center point regardless of zoom level.

My marker is a subview of the UIImageView that holds my map. It sounds like you are doing it the same way, so I imagine this (or something similar) should work for you.

like image 78
Katfish Avatar answered Sep 29 '22 09:09

Katfish