We had previously implemented tapping to zoom and now we've decided to use icons instead that will zoom in on the center of whats currently being displayed, and we'd like to reuse the code we had for our tap to zoom since we want the same effect, but now we don't know what to pass as the centerpoint.
We're using the
(CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
method which used to accept a center cgpoint from the gesture recognizer that we used for tap zooming; however, since we're no longer using the gesture recognizer we're going to have to figure out what cgpoint to pass it. Also, this method worked for the tap zoom so I don't think this is where we're having the problem.
We tried doing this
centerPoint = [scrollView contentOffset];
centerPoint.x += [scrollView frame].size.width / 2;
centerPoint.y += [scrollView frame].size.height / 2;
CGRect zoomRect = [self zoomRectForScale:newScale withCenter:centerPoint];
Which should calculate the current center and then pass it to zoomRectForScale, however it doesn't work (it zooms way to the right of the center).
I think that the problem probably has something to do with the fact that we're passing the center of the image before zoom is applied, and perhaps we're supposed to be passing a scaled center. Does anyone have any experience with this, or have any ideas on how we should be calculating the center?
We got it working and I thought I'd post what we ended up doing
/**
Function for the scrollview to be able to zoom out
**/
-(IBAction)zoomOut {
float newScale = [scrollView zoomScale] / ZOOM_STEP;
[self handleZoomWith:newScale andZoomType: FALSE];
}
/**
Function for the scrollview to be able to zoom in
**/
-(IBAction)zoomIn {
float newScale = [scrollView zoomScale] * ZOOM_STEP;
[self handleZoomWith:newScale andZoomType: TRUE];
}
-(void)handleZoomWith: (float) newScale andZoomType:(BOOL) isZoomIn {
CGPoint newOrigin = [zoomHandler getNewOriginFromViewLocation: [scrollView contentOffset]
viewSize: scrSize andZoomType: isZoomIn];
CGRect zoomRect = [self zoomRectForScale:newScale withCenter:newOrigin];
[scrollView zoomToRect:zoomRect animated:YES];
}
and then in a zoomHandler class we had this
-(CGPoint) getNewOriginFromViewLocation: (CGPoint) oldOrigin
viewSize: (CGPoint) viewSize
andZoomType:(BOOL) isZoomIn {
/* calculate original center (add the half of the width/height of the screen) */
float oldCenterX = oldOrigin.x + (viewSize.x / 2);
float oldCenterY = oldOrigin.y + (viewSize.y / 2);
/* calculate the new center */
CGPoint newCenter;
if(isZoomIn) {
newCenter = CGPointMake(oldCenterX * zoomLevel, oldCenterY * zoomLevel);
} else {
newCenter = CGPointMake(oldCenterX / zoomLevel, oldCenterY / zoomLevel);
}
/* calculate the new origin (deduct the half of the width/height of the screen) */
float newOriginX = newCenter.x - (viewSize.x / 2);
float newOriginY = newCenter.y - (viewSize.y / 2);
return CGPointMake(newOriginX, newOriginY);
}