我们之前实现了点击缩放,现在我们决定使用图标来代替,它会放大当前显示的内容的中心,我们想重用我们的点击缩放代码,因为我们想要相同的效果,但现在我们不知道传递什么作为中心点。
我们正在使用
(CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
用于从我们用于点击缩放的手势识别器接受中心 cgpoint 的方法;然而,由于我们不再使用手势识别器,我们将不得不弄清楚传递给它的 cgpoint。此外,此方法适用于点击缩放,因此我认为这不是我们遇到问题的地方。
我们试过这样做
centerPoint = [scrollView contentOffset];
centerPoint.x += [scrollView frame].size.width / 2;
centerPoint.y += [scrollView frame].size.height / 2;
CGRect zoomRect = [self zoomRectForScale:newScale withCenter:centerPoint];
它应该计算当前中心,然后将其传递给 zoomRectForScale,但它不起作用(它向中心右侧缩放)。
我认为这个问题可能与我们在应用缩放之前通过图像中心这一事实有关,也许我们应该通过缩放中心。有没有人对此有任何经验,或者对我们应该如何计算中心有任何想法?
最佳答案
我们成功了,我想我应该发布我们最终做的事情
/**
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];
}
然后在 zoomHandler 类中我们有这个
-(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);
}
关于ios - 如何使用 ScrollView 缩放到中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5807203/