What I want is a UIScrollView that has a repeating tiled image as a background.
The obvious answer to this question is as follows:
myScrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"myRepeatingImage.png"]];
However, this solution has multiple problems…
- Performance is terrible.
- It does not “work” with zooming correctly.
My next thought is to add a UIView (we’ll call it backgroundView) to myScrollView with a repeating image as a background color, and add all subviews to the backgroundView. However, this could get really messy with constantly resizing the backgroundView so that when a user zooms out (even temporarily beyond the minimum zoom level), you cannot see “around” the backgroundView.
Any suggestions?
Similar to this question, but the question was unanswered
UIScrollView with pattern image as background
I think this is what you’ll want to do.
Put some number (z) of UIImageView’s as the background. Extract these into a separate control so you only have to add one “background view”. Say you want to scroll up, down, left, and right. You also want to zoom out beyond the content size. So, you need x amount of images to cover your scroll views width, and s images to buffer the width on a zoom. (y to cover height and t to buffer height, so z = x + r + y + t)
Side note: When I say buffer the width, I mean put the images at an origin that lies outside the bounds of the content size. That way when zooming out past the content bounds, you will see these images, and not “around” the background.
When you scroll to the right a sufficient distance (based on your image size related to the scroll view bounds, or what is the visible frame), then move the now none visible image view to the right side of the right-most image view. Do the analogous thing for scrolling left, up, and down. You might need to add/remove image views when zooming occurs… or just use the maximum number of image views needed at all times.
The point is to increase performance, so ideally the number of image views your working with is small. The number increases proportionally to sizeof(scrollview.bounds)/sizeof(image). sizeof meaning frame size, not bytes, naturally.
EDIT:
To help illustrate this concept, we might make the following analogy. The scrollview is a lens looking in at part of a tiled floor, the content background of the scrollview is the tiled floor. However, we are only using a sufficient amount of tiles based on the lens. As the lens moves, we move non-visible tiles into areas where the lens will move to. As the lens zooms out, we add tiles (if removing them as we zoom in). I hope that helps clear things up instead of make it more confusing.