如何在 ScrollView 中垂直居中图像?
我在 Xcode 5 中使用 Storyboard。主视图嵌入在导航 Controller 内,并且在主 Storyboard中启用了“调整 ScrollView 插入”选项。该主视图有一个scrollView,其大小等于主视图大小。
imageView位于scrollView内部,并且与scrollView大小相同。内容模式设置为 AspectFit。
因此,层次结构如下:
- UINavigationController
- UIView
- UIScrollView
- UIImageView
图像可以是横向或纵向,并且可以是任何尺寸(在运行时加载)。这就是为什么 imageView 与scrollView 的大小相同。
如何使 ScrollView 中的图像垂直居中?
编辑: 正如之前评论的,我已将 imageView 的 contentMode 设置为 AspectFit,因为图像可能太大,所以我需要调整它的大小。我遇到的问题是图像不是 ScrollView 的中心。
最佳答案
正如@Douglas 提到的那样,使用自动布局会很好。但是,如果您更喜欢传统方式,也可以使其发挥作用。
我先给你答案,然后再向你解释。您应该首先从 Storyboard中删除 ImageView (我稍后会解释),然后添加 viewWillAppear
方法。
- (void)viewDidLoad
{
[super viewDidLoad];
// 1. Add the image view programatically
UIImageView * imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"portrait.jpg"]];
[_scrollView addSubview:imageView];
_imageView = imageView;
}
- (void)viewWillAppear:(BOOL)animated
{
// 2. calculate the size of the image view
CGFloat scrollViewWidth = CGRectGetWidth(_scrollView.frame);
CGFloat scrollViewHeight = CGRectGetHeight(_scrollView.frame);
CGFloat imageViewWidth = CGRectGetWidth(_imageView.frame);
CGFloat imageViewHeight = CGRectGetHeight(_imageView.frame);
CGFloat widthRatio = scrollViewWidth / imageViewWidth;
CGFloat heightRation = scrollViewHeight / imageViewHeight;
CGFloat ratio = MIN(widthRatio, heightRation);
CGRect newImageFrame = CGRectMake(0, 0, imageViewWidth * ratio, imageViewHeight * ratio);
_imageView.frame = newImageFrame;
// 3. find the position of the imageView.
CGFloat scrollViewCenterX = CGRectGetMidX(_scrollView.bounds);
CGFloat scrollViewCenterY = CGRectGetMidY(_scrollView.bounds) + _scrollView.contentInset.top / 2 ;
_imageView.center = CGPointMake(scrollViewCenterX, scrollViewCenterY);
}
解释如下:
不应该将imageView放在storyboard中,否则imageView的frame会被storyboard固定,不会随着图像的大小而改变。即使选择
UIViewContentModeScaleAspectFill
,imageView的框架仍然没有改变。它只是在图像周围添加一些空白。现在 imageView 的大小与您的图像相同。如果想要完全显示,就需要自己计算帧数。
注意
_scrollView.contentInset.top/2
,这就是为什么你需要将代码放在viewWillAppear
而不是viewDidLoad
。_scrollView.contentInset.top
是导航栏的高度,在willViewAppear
之前自动计算。
你把你的 ImageView 放在一个 ScrollView 中,我猜你想放大和缩小。如果是这样,请添加 self.imageView = imageView;
和 viewDidLoad
的底部。将_scrollView
的委托(delegate)设置为self
并添加以下方法:
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return _imageView;
}
关于ios - imageView 在scrollView 内居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623557/