iOS简单、可用的图片浏览组件

前言

  • 对于一个新入门的iOS开发而言,在学会了语法、了解了常用控件、会制作简单的界面以后,做一个图片浏览的组件是一个相当不错的练习课题。

  • 图片浏览组件的开源实现,无论是功能完善的、还是简单实用的,都已经很多,且相关的博客也很多,但这不否定学习的必要性,学习不能只会调包。

  • 现在常用的app中,几乎都包含图片浏览的功能,如果你也想完成实用的图片浏览,但又不需要引入过多的过渡动画,这份文档会帮助到你。

  • 参考了开源实现https://github.com/cuzv/PhotoBrowser,感谢作者。

需求

  • 单张图片:黑色背景,图片宽度顶格到屏幕的宽度,高度按比例放缩,双击图片可以放大,再次双击可以还原,双指捏合也可以放大和缩小,放大时可以拖动

  • 图片序列:做好了单张图片的功能,就需要它们可以按顺序的滑动切换,另外还需要一个显示当前页和总页数的控件,可以是圆圈或数字。(除此之外,往往还需要点击保存、长按保存、分享的功能,本文都没有涉及)

  • 过渡:点击了某张小图后,可以淡入的弹出图片浏览,再次单击,可以淡出的消失。

  • 对外接口:支持两种方式调用,一是传入UIImage的数组,二是传入NSURL的数组。

实现

对于单张图片的需求,概括起来就是放缩和拖动,配合ScrollView来实现会简单很多。创建一个普通的ViewController(不妨称之为SinglePhotoViewController),子View是ScrollView,再把ImageView作为ScrollView的子View。

- (UIScrollView *)scrollView {
    if(_scrollView == nil){
        _scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        if (@available(iOS 11.0, *)) {
            _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _scrollView.multipleTouchEnabled = YES;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.alwaysBounceVertical = YES;
        _scrollView.alwaysBounceHorizontal = NO;
        _scrollView.minimumZoomScale = 1.0f;
        _scrollView.maximumZoomScale = 3.0f;
        _scrollView.delegate = self;
    }
    return _scrollView;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [UIImageView new];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.clipsToBounds = YES;
    }
    return _imageView;
}

ScrollView默认提供了放缩的功能,首先需要实现一个delegate方法,指出哪个subView随之放缩:

// MARK: - UIScrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}

这里ScrollView和ImageView的frame、contentSize等属性,都还没有指定,而是等拿到需要的Image数据的时候再指定,那么什么时候拿到Image数据呢,拿到的又是什么数据?

  • 拿到的数据有两种,已有的Image和NSURL
  • 不管哪种数据源,第一张图片数据(image或url),是在界面present的时候拿到,后续的图片,是在左右滑动切换的时候拿到
  • SinglePhotoViewController的数据来源,是它的父VC,继承自UIPageViewController,后面会讲到
  • 如果拿到了image,可以直接刷新界面,如果拿到了url,需要先请求图片,在回调里刷新界面

因此,SinglePhotoViewController就要暴露一个方法,以供父VC在合适的时候刷新界面:

// 对外使用,分本地和网络图片两种情况,都在此处理
- (void)updateUI {
    if(self.image) {
        [self updateFrameWithLoadedImage];
    }
    else {
        [self loadImageAndUpdateFrame];
    }
}

需要的辅助函数如下:

// 请求网络图片,回调中更新frame
- (void)loadImageAndUpdateFrame {
    self.loadingLabel.hidden = NO;
    [[SDWebImageManager sharedManager] loadImageWithURL:self.imageURL options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        if(!error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.image = image;
                self.loadingLabel.hidden = YES;
                [self updateFrameWithLoadedImage];
            });
        }
    }];
}

// 本地已有图片时,直接更新frame
- (void)updateFrameWithLoadedImage {
    // 还原成一倍大小,初始状态或切换出去的时候
    [self.scrollView setZoomScale:1 animated:YES];
    // 宽度顶格,高度按比例
    CGFloat ratio = self.scrollView.bounds.size.width / self.image.size.width;
    CGSize properSize = CGSizeMake(self.scrollView.bounds.size.width, ceil(ratio * self.image.size.height));
    self.scrollView.contentSize = properSize;
    self.imageView.frame = CGRectMake(0, 0, properSize.width, properSize.height);
    self.imageView.image = self.image;
    // 图片中心调整,发生在初始或捏合的时候
    [self _recenterImage];
}

- (void)_recenterImage {
    CGFloat contentWidth = self.scrollView.contentSize.width;
    CGFloat horizontalDiff = CGRectGetWidth(self.scrollView.bounds) - contentWidth;
    CGFloat horizontalAddition = horizontalDiff > 0.f ? horizontalDiff : 0.f;
    
    CGFloat contentHeight = self.scrollView.contentSize.height;
    CGFloat verticalDiff = CGRectGetHeight(self.scrollView.bounds) - contentHeight;
    CGFloat verticalAdditon = verticalDiff > 0 ? verticalDiff : 0.f;

    self.imageView.center = CGPointMake((contentWidth + horizontalAddition) / 2.0f, (contentHeight + verticalAdditon) / 2.0f);
}

上面的loadImageAndUpdateFrame函数,主要是先显示出一个“正在加载”的label,然后拿到image后label消失,调用updateFrameWithLoadedImage更新frame、contentSize。

updateFrameWithLoadedImage中做的事情注释写的比较清楚, 下面主要说一下图片的recenter,调整中心位置。一个ScrollView,上下左右滑动能够覆盖到的区域,由contentSize决定,contentSize初始时就是图片宽度顶格,高度按比例那时候的size,而随着图片的放缩,contentSize也会变大变小,这时就需要根据contentSize调整图片的中心位置。也就是说,_recenterImage不只会在图片刚刚获取到的时候调用,在图片放大缩小的整个过程中,都会调用,这就是ScrollView的另外一个delegate方法:

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    [self _recenterImage]; // 图片放缩的过程中,持续调用recenter
}

如果不做这个recenter的操作,放缩时候的交互体验就很差。另外,我在参考其他人实现方式的时候,发现SinglePhotoViewController如果配合ScrollView来实现,基本都包括这个recenter的操作,而且函数实现,基本只是中间变量命名不同的差别。

到这里,SinglePhotoViewController的拖动图片和手指捏合已经实现了,还有以下没有讲到:

  • SinglePhotoViewController还需要拿到当前页的索引pageIndex,拿数据源的时候,顺便就拿到了
  • loadingLabel的设计,自己随意即可
  • 还差一个双击放大/还原的手势,我把它放到了父View,也就是UIPageViewController来实现,其实代码这样设计确实有些问题:一方面,单张图片的双击效果只和SinglePhotoViewController有关,与父VC无关;另外,把双击手势交给父VC,再来修改SinglePhotoViewController中的ScrollView和ImageView,这两个subView又不得不暴露出来。总之SingleVC和父VC,耦合在一起了,希望读者留意一下。

下面再来介绍父VC,继承自UIPageViewController,不妨称之为PhotoBrowser,是直接对外调用的,前面提到图片数据源可以是image或url,因此PhotoBrowser就要暴露两个初始化方法,头文件:

// 提供两个初始化方法:传入一个本地Image数组,或者传入一个图片URL数组,并指定当前index,然后直接present即可

- (instancetype _Nullable )initWithLocalImages: (NSArray <UIImage *> *_Nonnull)images currentIndex: (NSInteger)currentIndex;

- (instancetype _Nullable )initWithURLs: (NSArray <NSURL *> *_Nonnull)urls currentIndex: (NSInteger)currentIndex;

.m文件中的私有属性如下,其中indicatorLabel是用来显示页数的,例如“7/20”。

// 数据
@property (nonatomic, strong) NSArray<SinglePhotoViewController *> *subPages;
@property (nonatomic, strong) NSArray<UIImage *> *localImages;
@property (nonatomic, strong) NSArray<NSURL *> *imageURLs;
@property (nonatomic, assign, readwrite) NSInteger numberOfPages;
@property (nonatomic, assign, readwrite) NSInteger currentIndex;

// 页数显示
@property (nonatomic, strong) UILabel *indicatorLabel;
// Blur background view
@property (nonatomic, strong) UIView *blurBackgroundView;
// 手势
@property (nonatomic, strong) UITapGestureRecognizer *singleTapGestureRecognizer;
@property (nonatomic, strong) UITapGestureRecognizer *doubleTapGestureRecognizer;

构造函数实现,代码看起来比较多,但不复杂

- (instancetype)init {
    self = [super initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                    navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                  options:@{ UIPageViewControllerOptionInterPageSpacingKey: @20 }];
    if(self) {
        self.modalPresentationStyle = UIModalPresentationFullScreen;
        self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    }
    return self;
}

- (instancetype)initWithLocalImages:(NSArray<UIImage *> *)images currentIndex:(NSInteger)currentIndex {
    self = [self init];
    if(self) {
        self.localImages = images;
        self.imageURLs = nil;
        self.numberOfPages = images.count;
        self.currentIndex = (currentIndex < 0 || currentIndex >= self.numberOfPages) ? 0 : currentIndex;
    }
    return self;
}

- (instancetype)initWithURLs: (NSArray <NSURL *> *_Nonnull)urls currentIndex: (NSInteger)currentIndex {
    self = [self init];
    if(self) {
        self.imageURLs = urls;
        self.localImages = nil;
        self.numberOfPages = urls.count;
        self.currentIndex = (currentIndex < 0 || currentIndex >= self.numberOfPages) ? 0 : currentIndex;
    }
    return self;
}

私有属性的实现,代码看起来比较多,但不复杂,主要是看一下subPages的实例化过程,把图片数据源分发到每一个subPage,拿到数据源以后,需要的时候调用updateUI就好了,后面会讲到。

- (NSArray<SinglePhotoViewController *> *)subPages {
    if (_subPages == nil) {
        NSMutableArray *temp = [NSMutableArray new];
        for(int i = 0; i < self.numberOfPages; i++) {
            SinglePhotoViewController *nowSubPage = [SinglePhotoViewController new];
            if(self.localImages) { // 如果是本地图片
                nowSubPage.image = [self.localImages objectAtIndex:i];
                nowSubPage.imageURL = nil;
            }
            else { // 是网络图片
                nowSubPage.imageURL = [self.imageURLs objectAtIndex:i];
                nowSubPage.image = nil;
            }
            nowSubPage.pageIndex = i;
            [temp addObject:nowSubPage];
        }
        _subPages = [NSArray arrayWithArray: temp];
    }
    return _subPages;
}

- (UILabel *)indicatorLabel {
    if (_indicatorLabel == nil) {
        _indicatorLabel = [UILabel new];
        _indicatorLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightBold];
        _indicatorLabel.textColor = [UIColor whiteColor];
    }
    return _indicatorLabel;
}

- (UIView *)blurBackgroundView {
    if (!_blurBackgroundView) {
        _blurBackgroundView = [[UIView alloc] initWithFrame:self.view.bounds];
        _blurBackgroundView.backgroundColor = [UIColor blackColor];
        _blurBackgroundView.userInteractionEnabled = NO;
    }
    return _blurBackgroundView;
}

- (UITapGestureRecognizer *)singleTapGestureRecognizer {
    if (!_singleTapGestureRecognizer) {
        _singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_handleSingleTapAction:)];
    }
    return _singleTapGestureRecognizer;
}

- (UITapGestureRecognizer *)doubleTapGestureRecognizer {
    if (!_doubleTapGestureRecognizer) {
        _doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_handleDoubleTapAction:)];
        _doubleTapGestureRecognizer.numberOfTapsRequired = 2;
    }
    return _doubleTapGestureRecognizer;
}

在viewDidLoad时候,做一些常规的操作,_updateIndicator是用来更新页数索引,当滑动切换图片的时候,也会调用。

- (void)viewDidLoad {
    [super viewDidLoad];
    
    SinglePhotoViewController *currentPage = [self.subPages objectAtIndex:self.currentIndex];
    [currentPage updateUI];
    [self setViewControllers:@[currentPage] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];

    // 页数指示器
    [self.view addSubview:self.indicatorLabel];
    self.indicatorLabel.layer.zPosition = 1024;
    [self _updateIndicator];
    // 黑色背景
    [self.view addSubview:self.blurBackgroundView];
    [self.view sendSubviewToBack:self.blurBackgroundView];
    // 手势
    [self.view addGestureRecognizer:self.doubleTapGestureRecognizer];
    [self.view addGestureRecognizer:self.singleTapGestureRecognizer];
    [self.singleTapGestureRecognizer requireGestureRecognizerToFail:self.doubleTapGestureRecognizer];
    // 协议
    self.dataSource = self;
    self.delegate = self;
}

- (void)_updateIndicator {
    self.indicatorLabel.text = [NSString stringWithFormat:@"%@ / %@", @(self.currentIndex + 1), @(self.numberOfPages)];
    [self.indicatorLabel sizeToFit];
    self.indicatorLabel.center = CGPointMake(self.view.bounds.size.width / 2, 72);
}

单击手势,让PageVC进行dismiss即可:

- (void)_handleSingleTapAction:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

双击手势就比较复杂了,主要是放大的操作。我设定了maximumZoomScale = 3,也就是图片最大可以放大3倍,具体来说,就是要生成一个CGRect,它的宽高分别是屏幕宽高的1/3,而这个CGRect的中心,就是手指的触摸点,然后调用zoomToRect,根据刚才的CGRect进行放大。这里耦合的问题,之前已经提到了。

- (void)_handleDoubleTapAction:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        SinglePhotoViewController *nowPage = [self.subPages objectAtIndex: self.currentIndex];
        UIScrollView *nowScrollView = nowPage.scrollView;
        UIImageView *nowImageView = nowPage.imageView;
        
        if (nowScrollView.zoomScale > 1) {  // 如果已经放大了,那么还原到1倍
            [nowScrollView setZoomScale:1 animated:YES];
        }
        else if (nowScrollView.maximumZoomScale > 1) { // 否则将会放大
            CGPoint touchPoint = [self.view convertPoint:[sender locationInView:self.view] toView:nowImageView];
            CGFloat newZoomScale = nowScrollView.maximumZoomScale;
            CGFloat horizontalSize = nowScrollView.bounds.size.width / newZoomScale;
            CGFloat verticalSize = nowScrollView.bounds.size.height / newZoomScale;
            [nowScrollView zoomToRect:CGRectMake(touchPoint.x - horizontalSize / 2.0f, touchPoint.y - verticalSize / 2.0f, horizontalSize, verticalSize) animated:YES];
        }
    }   
}

接下来是PageViewController的两个datasource方法, 是必须要实现的,取出后一页和前一页。这里每一个subPage所需要的image/url、index,已经在self.subPages实例化的时候,分发下去了。

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(SinglePhotoViewController *)viewController {
    if(viewController.pageIndex == 0) { // 如果已经是第一页
        return nil;
    }
    return [self.subPages objectAtIndex:viewController.pageIndex - 1];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(SinglePhotoViewController *)viewController {
    if(viewController.pageIndex == self.numberOfPages - 1) { // 如果已经是最后一页
        return nil;
    }
    return [self.subPages objectAtIndex:viewController.pageIndex + 1];
}

接下来是PageViewController的两个delegate方法,分别实现了将要切换和切换结束的动作,做的事情也比较简单,由于根据图片数据源(image或url)刷新SingleVC的界面,已经交给了updateUI并暴露出来,这里调用一下就可以了。

- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    // 即将滑到下一页
    SinglePhotoViewController *nextPage = (SinglePhotoViewController *)pendingViewControllers.firstObject;
    [nextPage updateUI];
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {
    // 已经滑到下一页,更新currentIndex 和 页数标签
    SinglePhotoViewController *nowPage = pageViewController.viewControllers.firstObject;
    self.currentIndex = nowPage.pageIndex;
    [self _updateIndicator];
}

总结

以上就是全部的实现过程,由于某些原因,就不提供源文件了,但是核心的代码,基本都在上面讲到了,总共不到400行,完成了图片浏览所需要的核心功能,用了5天时间,是我实习以来的第一份阶段性成果,感谢mentor。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容