I have an UIImageView in an UIScrollView, and the image has size say 2000×3000. I can pinch to zoom and drag to pan on the screen. (I followed this video https://www.youtube.com/watch?v=0Tz0vI721c8).
My question is if I want to center the display at a point on the image programmatically (i.e. 600, 800), I think I need to use scrollView.setContentOffset(CGPoint), how do I figure out the CGPoint?
2
Answers
You have to take a couple things into account, beyond just setting the
.contentOffset
to match the "target center point" …First, the goal…
Using this
2000 x 3000
image:"
With this set of "center points":
We want to programmatically set the centers to the center of the scroll view:
If all we did was set the
.contentOffset
to the "target point" for #3, we’d get this:So, we need to subtract one-half of the width and height of the scroll view frame:
That puts our "target point" in the center of the scroll view, but…
If we’ve zoomed out to, say, 90% (
scrollView.zoomScale = 0.9
), we get this:So, we need to translate the "target point" to the zoom scale:
and, woo hoo, we have this:
The next problem, though, is that we don’t want to center the "target point" if that would exceed the scroll view limits.
For example, if we try to center on "1" or "5" we get:
and:
the Points are centered in the scroll view, but as soon as we touch it to scroll or zoom, it will snap to the corner.
We need to limit the
.contentOffset
to avoid that.So, for point "1" (
points[0]
):Here’s a complete example… as in the above images, tapping a "Number Button" will scroll that center point to the center of the scroll view (or as close as possible, if it would exceed the limits). All you need is to add that 2000×3000 image (named "img2000x3000") … no
@IBOutlet
or@IBAction
connections needed: