如何在 ScrollView 中居中 UIImageView(缩放)

Posted

技术标签:

【中文标题】如何在 ScrollView 中居中 UIImageView(缩放)【英文标题】:How to center UIImageView in ScrollView (Zooming) 【发布时间】:2012-11-01 19:20:35 【问题描述】:

我正在尝试在UIScrollView 中缩放 UIImageView。我有这个:

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView 
return imageView;


-(void)scrollViewDidZoom:(UIScrollView *)scrollView 
[imageView setCenter:CGPointMake(scrollView.center.x, scrollView.center.y)];


-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale 

问题是:当我缩小图像时它居中,但是当我放大时,图像移动到左上角。

我的代码哪里出了问题?

【问题讨论】:

【参考方案1】:

答案是从scrollViewDidZoom: 中删除所有内容并添加:

[self centerScrollViewContent];

方法实现:

- (void)centerScrollViewContents 
CGSize boundsSize = self.scrollView.bounds.size;
CGRect contentsFrame = self.containerView.frame;

if (contentsFrame.size.width < boundsSize.width) 
    contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
 else 
    contentsFrame.origin.x = 0.0f;


if (contentsFrame.size.height < boundsSize.height) 
    contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
 else 
    contentsFrame.origin.y = 0.0f;


self.containerView.frame = contentsFrame;

【讨论】:

以上是关于如何在 ScrollView 中居中 UIImageView(缩放)的主要内容,如果未能解决你的问题,请参考以下文章