OGeek|极客世界-中国程序员成长平台

标题: ios - imageView 在 scrollView 内居中 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:40
标题: ios - imageView 在 scrollView 内居中

如何在 ScrollView 中垂直居中图像?

我在 Xcode 5 中使用 Storyboard 。主视图嵌入在导航 Controller 中,并且在主 Storyboard 中启用了“调整 ScrollView 插图”选项。这个主视图有一个 ScrollView ,它的大小等于主视图的大小。

imageView 位于 scrollView 内部,与 scrollView 大小相同。内容模式设置为 AspectFit。

所以,层次结构如下:

- UINavigationController
- UIView
   - UIScrollView
       - UIImageView

图像可以是横向或纵向的,并且可以是任意大小(在运行时加载)。这就是为什么 imageView 和 scrollView 大小一样的原因。

如何在 scrollView 内垂直居中图像?

编辑: 如前所述,我已将 imageView 的 contentMode 设置为 AspectFit,因为图像可能太大,所以我需要调整它的大小。我遇到的问题是图像不是 ScrollView 的中心。

您可以在link查看截图并在 link 下载源代码.



Best Answer-推荐答案


使用@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)viewWillAppearBOOL)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);
    }    

解释如下:

  1. 不应该把imageView放在storyboard中,否则imageView的frame会被storyboard固定,不会随着图片的大小而变化。即使选择了UIViewContentModeScaleAspectFill,imageView的frame依然没有改变。它只是在图像周围添加一些空白区域。

  2. 现在 imageView 的大小与您的图像相同。如果你想让它完全显示,你需要自己计算框架。

  3. 注意_scrollView.contentInset.top/2,这就是为什么你需要把代码放在viewWillAppear而不是viewDidLoad_scrollView.contentInset.top 是导航栏的高度,在 willViewAppear 之前自动为您计算。

你把你的 ImageView 放在一个 ScrollView 中,我猜你想放大和缩小。如果是这样,添加 self.imageView = imageView;viewDidLoad 的底部。将_scrollView的delegate设置为self,并添加如下方法:

    - (UIView *)viewForZoomingInScrollViewUIScrollView *)scrollView
    {
        return _imageView;
    }

关于ios - imageView 在 scrollView 内居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623557/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4