Zoom unscaled views in UIScrollView to bounds Zoom unscaled views in UIScrollView to bounds objective-c objective-c

Zoom unscaled views in UIScrollView to bounds


I downloaded your project and found the following issues:

When you initialize zoomingView, you set the origin of its frame so that zoomingView is in the middle of the scrollView. When you then scale the scrollView, it does also scale the offsets to the origin, which had to be taken into account for the correct placement of the scaled zoomingView.

I think it is clearer if you set the origin to 0:

self.zoomingView = [[ZoomingView alloc] initWithFrame:CGRectMake(0, 0, kZoomingViewWidth, kZoomingViewHeight)];

After scaling the zoomingView you had to center it. This can be done e.g. by

self.scrollView.zoomScale = scaleFactor;    CGRect svb = self.scrollView.bounds;    CGRect zvf = self.zoomingView.frame;    self.scrollView.bounds = CGRectMake((zvf.size.width - svb.size.width)/2.0, (zvf.size.height - svb.size.height)/2.0, svb.size.width, svb.size.height);

Then the following function becomes very simple:

- (void)scrollViewDidZoom:(UIScrollView *)scrollView{   [self.zoomingView handleZoom:scrollView.zoomScale];}

With these modifications, the scaled zoomingView is centered correctly.

However, the scaling factor is still wrong since the inner green rect is scaled to fill the available space. The reason is that one has to consider that 2 boxes of size 30 have to be visible additionally, i.e. the available space for scaling is smaller. This can be done e.g. by

CGFloat scaleFactor = newSize.height == scrollViewHeight    ? (scrollViewHeight - 60.0) / viewHeight    : (scrollViewWidth - 60.0) / viewWidth;

Of course, the constants had to be replaced by variables later.

With these modifications, your code runs correctly for me.

One more thing: This excellent post discusses in detail scroll views.


What if change anchorPoints to values:

NSArray *anchorPoints = @[[NSValue valueWithCGPoint:CGPointMake(0.0, 0.0)],                          [NSValue valueWithCGPoint:CGPointMake(0.5, 0.0)],                          [NSValue valueWithCGPoint:CGPointMake(1.0, 0.0)],                          [NSValue valueWithCGPoint:CGPointMake(0.0, 0.5)],                          [NSValue valueWithCGPoint:CGPointMake(0.5, 0.5)],                          [NSValue valueWithCGPoint:CGPointMake(1.0, 0.5)],                          [NSValue valueWithCGPoint:CGPointMake(0.0, 1.0)],                          [NSValue valueWithCGPoint:CGPointMake(0.5, 1.0)],                          [NSValue valueWithCGPoint:CGPointMake(1.0, 1.0)]                          ];

So you will adjust your views to the edges of zooming view and get what you want:

Result