写在之前:以下分享的内容有部分是参考网上开源代码。
废话不多说,直接看效果:
QQ20170428-161825.gif这个gif居然要控制在5M内,蛋疼- - 。
看完效果,如果你敢兴趣的话,就可以往下看。
代码分析:
整体可以分为三个模块:
6A30B1B0-D330-420A-B96C-B81A3C9BF4A4.pngSLPhotoContainerView
它就是显示9宫格图片的载体,一个view。
看看代码:
.h
#import <UIKit/UIKit.h>
@interface SLPhotoContainerView : UIView
@property (strong, nonatomic) NSMutableArray *picUrlArray;
@end
这里定义了一个数组,用于存图片的URL。
.m
#import "SLPhotoContainerView.h"
#import "SLPhotoBrowser.h"
#import "UIView+Frame.h"
#import "Masonry.h"
static NSUInteger const MaxPicCount = 9;
@interface SLPhotoContainerView ()
<
SLPhotoBrowserDelegate
>
@property (strong, nonatomic) NSMutableArray *imageViewArray;
@end
首先声明了一个常量,图片数量最多9张。这有个代理,我们后面会说。还声明了个数组,用于保存view
上add的UIImageView
。
方法的实现:
- (void)setupImageView {
NSMutableArray *temp = [NSMutableArray new];
//最多9张图片,初始化imageView
for (int i = 0; i < MaxPicCount; i ++) {
UIImageView *imageView = [UIImageView new];
[self addSubview:imageView];
imageView.userInteractionEnabled = YES;
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;
imageView.tag = i;
//添加手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickedImageView:)];
[imageView addGestureRecognizer:tap];
//放入到数组中
[temp addObject:imageView];
}
self.imageViewArray = [temp copy];
}
初始化add9个UIImageView
,将其全部保存到数组中。
- (void)setPicUrlArray:(NSMutableArray *)picUrlArray {
_picUrlArray = picUrlArray;
//隐藏多余的imageView
for (long i = [_picUrlArray count]; i < [_imageViewArray count]; i ++) {
UIImageView *imageView = _imageViewArray[i];
imageView.hidden = YES;
}
//如果没图片返回高度为0
if ([_picUrlArray count] == 0) {
self.height = 0;
return;
}
//图片的宽度和高度一样 每行最多3张
CGFloat width = (self.width - 20)/3;
CGFloat height = width;
CGFloat margin = 10;
//枚举
[_picUrlArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//列数 行数
NSInteger columnIndex = idx % 3;
NSInteger rowIndex = idx / 3;
UIImageView *imageView = _imageViewArray[idx];
imageView.hidden = NO;
imageView.frame = CGRectMake(columnIndex * (width + margin), rowIndex * (height + margin), width, height);
NSString *imgUrl = _picUrlArray[idx];
[imageView sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:PLACEHOLDERPNG];
}];
NSInteger column = [self columnCountForArray:_picUrlArray];
CGFloat w = column * (width + margin);
NSInteger row = [self rowCountForArray:_picUrlArray];
CGFloat h = row * (height + margin);
[self mas_updateConstraints:^(MASConstraintMaker *make) {
make.size.mas_equalTo(CGSizeMake(w, h));
make.left.offset(50);
make.top.offset(100);
}];
}
这是初始化URL数组,首先给数组赋值,然后隐藏掉多余的UIImageView
,再之后就计算图片会显示多少列,多少行。最后去更新本身的大小。
- (void)clickedImageView:(UITapGestureRecognizer *)tap {
SLPhotoBrowser *browser = [[SLPhotoBrowser alloc] init];
browser.currentImageIndex = tap.view.tag;
browser.sourceImagesContainerView = self;
browser.imageCount = self.picUrlArray.count;
browser.delegate = self;
//显示大图浏览
[browser show];
}
点击图片,跳转到我们的第二模块。
SLPhotoBrowser
它是浏览大图的载体。
看看代码:
.h
#import "SLBrowserImageView.h"
#import "SLPhotoBrowserConfig.h"
@class SLPhotoBrowser;
@protocol SLPhotoBrowserDelegate <NSObject>
@required
- (UIImage *)photoBrowser:(SLPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index;
@optional
- (NSURL *)photoBrowser:(SLPhotoBrowser *)browser imageURLForIndex:(NSInteger)index;
@end
@interface SLPhotoBrowser : UIView
@property (nonatomic, weak) UIView *sourceImagesContainerView;
@property (nonatomic, assign) NSInteger currentImageIndex;
@property (nonatomic, assign) NSInteger imageCount;
@property (nonatomic, weak) id<SLPhotoBrowserDelegate> delegate;
- (void)show;
@end
申明了一个UIView
,其实它就是我们之前的SLPhotoContainerView
。然后声明了个delegate
以及两个代理方法。一个是用于获取到SLPhotoContainerView
的UIImage
,一个是获取URL。
.m
@interface SLPhotoBrowser ()
<
UIScrollViewDelegate
>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, assign) BOOL hasShowedFistView;
@end
因为需要滑动,所以这声明了UIScrollView
。
- (void)show {
UIWindow *window = [UIApplication sharedApplication].keyWindow;
self.frame = window.bounds;
//监听frame
[window addObserver:self forKeyPath:@"frame" options:0 context:nil];
[window addSubview:self];
}
这个是点击小图调用的方法,我们把self
add 到UIWindow
,然后会调用下面的方法
//当视图移动完成之后会调用该方法
- (void)didMoveToSuperview {
[self initWithScrollView];
[self initWithPageControl];
}
- (void)initWithScrollView {
[self addSubview:self.scrollView];
for (int i = 0; i < self.imageCount; i++) {
SLBrowserImageView *imageView = [[SLBrowserImageView alloc] init];
imageView.tag = i;
// 单击图片
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageClicked:)];
[imageView addGestureRecognizer:singleTap];
//双击图片,用于图片放大查看
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewDoubleTaped:)];
doubleTap.numberOfTapsRequired = 2;
// 关键在这一行,双击手势确定监测失败才会触发单击手势的相应操作
[singleTap requireGestureRecognizerToFail:doubleTap];
[imageView addGestureRecognizer:doubleTap];
[self.scrollView addSubview:imageView];
}
//加载当前点击的图片
[self setupImageForIndex:self.currentImageIndex];
}
- (void)initWithPageControl {
self.pageControl.numberOfPages = _imageCount;
self.pageControl.currentPage = _currentImageIndex;
[self addSubview:self.pageControl];
}
初始化,UIScrollView
add SLBrowserImageView
,SLBrowserImageView
就是我们的第三个模块,后面再详解SLBrowserImageView
。这里的代码并不复杂,应该很好理解。
//加载图片
- (void)setupImageForIndex:(NSInteger)index {
SLBrowserImageView *imageView = self.scrollView.subviews[index];
self.currentImageIndex = index;
//图片加载过
if (imageView.hasLoadedImage) {
return;
}
//利用代理 拿到url
if ([self imageURLForIndex:self.currentImageIndex]) {
[imageView setImageWithURL:[self imageURLForIndex:self.currentImageIndex] placeholderImage:[self placeholderImageForIndex:index]];
} else {
imageView.image = [self placeholderImageForIndex:index];
}
//设置为图片已加载
imageView.hasLoadedImage = YES;
}
上面是加载图片的方法。
- (void)layoutSubviews {
[super layoutSubviews];
CGRect rect = self.bounds;
//在滑动的时候,图片和图片之前保持20像素的间隔
rect.size.width += SLPhotoBrowserImageViewMargin*2;
self.scrollView.bounds = rect;
self.scrollView.center = self.center;
CGFloat y = 0;
CGFloat w = _scrollView.frame.size.width - SLPhotoBrowserImageViewMargin * 2;
CGFloat h = _scrollView.frame.size.height;
[_scrollView.subviews enumerateObjectsUsingBlock:^(SLBrowserImageView *obj, NSUInteger idx, BOOL *stop) {
//遍历,设置图片的frame
CGFloat x = SLPhotoBrowserImageViewMargin + idx * (SLPhotoBrowserImageViewMargin * 2 + w);
obj.frame = CGRectMake(x, y, w, h);
}];
_scrollView.contentSize = CGSizeMake(_scrollView.subviews.count * _scrollView.frame.size.width, 0);
_scrollView.contentOffset = CGPointMake(self.currentImageIndex * _scrollView.frame.size.width, 0);
if (!_hasShowedFistView) {
//重要,设置动画效果
[self showFirstImage];
}
}
下面这个方法比较重要,有了它才有了点击放大的动画效果。
- (void)showFirstImage
{
UIView *sourceView = self.sourceImagesContainerView.subviews[self.currentImageIndex];
// 获取点击图片的坐标及大小
CGRect rect = [self.sourceImagesContainerView convertRect:sourceView.frame toView:self];
// 创建一个临时imageview
UIImageView *tempView = [[UIImageView alloc] init];
// 获取点击的image
tempView.image = [self placeholderImageForIndex:self.currentImageIndex];
[self addSubview:tempView];
// 放大的坐标及大小
CGRect targetTemp = [_scrollView.subviews[self.currentImageIndex] bounds];
tempView.frame = rect;
tempView.contentMode = [_scrollView.subviews[self.currentImageIndex] contentMode];
_scrollView.hidden = YES;
// 放大动画
[UIView animateWithDuration:SLPhotoBrowserShowImageAnimationDuration animations:^{
tempView.center = self.center;
tempView.bounds = (CGRect){CGPointZero, targetTemp.size};
} completion:^(BOOL finished) {
// 动画完成之后,临时imageview 移除掉
_hasShowedFistView = YES;
[tempView removeFromSuperview];
_scrollView.hidden = NO;
}];
}
这个就是点击放大的动画,它就是生成了一个临时UIImageView
从小图到大图的frame
变化,在动画完成之后,因为UIScrollView
上的图片也加载完成,所以就可以把临时的UIImageView
移除掉。点击大图缩放到小图,和这个是一个原理,这里我就不多讲了。来说说第三个模块。
SLBrowserImageView
它就是一个UIImageView
,是最终放大后显示的图片。 来看看代码:
.h
#import <UIKit/UIKit.h>
#import "UIImageView+WebCache.h"
@interface SLBrowserImageView : UIImageView
/**
是否缩放
*/
@property (nonatomic, assign, readonly) BOOL isScaled;
@property (nonatomic, assign) BOOL hasLoadedImage;
// 清除缩放
- (void)eliminateScale;
// 加载图片
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;
// 双击图片之后会调用
- (void)doubleTapToZommWithScale:(CGFloat)scale;
- (void)clear;
@end
.m
#import "SLBrowserImageView.h"
#import "SLWaitingView.h"
@interface SLBrowserImageView ()
<
UIGestureRecognizerDelegate
>
/**
图片的高度超过屏幕的高 就添加到scrollView,然后可以滑动。
*/
@property (nonatomic, strong) UIScrollView *scrollView;
/**
图片的高度超过屏幕的高,添加到scrollView的图片。
*/
@property (nonatomic, strong) UIImageView *scrollImageView;
/**
捏合或者双击手势缩放图片之后 就添加到zoomingScrollView,然后可以滑动。
*/
@property (nonatomic, strong) UIScrollView *zoomingScrollView;
/**
捏合或者双击手势缩放图片之后 添加zoomingScrollView的图片
*/
@property (nonatomic, strong) UIImageView *zoomingScrollImageView;
/**
图片缩放倍数,默认1
*/
@property (nonatomic, assign) CGFloat totalScale;
/**
菊花
*/
@property (nonatomic, strong) SLWaitingView *waitingView;
@end
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
//加一个菊花
UIWindow *window = [UIApplication sharedApplication].delegate.window;
self.waitingView = [[SLWaitingView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
self.waitingView.center = window.center;
[self.waitingView.indicatorView startAnimating];
[self addSubview:self.waitingView];
__weak SLBrowserImageView *imageViewWeak = self;
SDWebImageOptions options = SDWebImageRetryFailed | SDWebImageLowPriority | SDWebImageProgressiveDownload;
[self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//这里可以显示进度图
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
[imageViewWeak.waitingView removeFromSuperview];
if (error) {
NSLog(@">>> error");
} else {
//图片的高度超过屏幕的高 就添加到scrollView
imageViewWeak.scrollImageView.image = image;
[imageViewWeak.scrollImageView setNeedsDisplay];
}
}];
}
加载图片。
- (void)zoomImage:(UIPinchGestureRecognizer *)recognizer
{
//捏合手势缩放图片
[self prepareForImageViewScaling];
CGFloat scale = recognizer.scale;
CGFloat temp = _totalScale + (scale - 1);
[self setTotalScale:temp];
recognizer.scale = 1.0;
}
- (void)setTotalScale:(CGFloat)totalScale {
if ((_totalScale < 0.5 && totalScale < _totalScale) || (_totalScale > 2.0 && totalScale > _totalScale)) return; // 最大缩放 2倍,最小0.5倍
[self zoomWithScale:totalScale];
}
- (void)doubleTapToZommWithScale:(CGFloat)scale {
[self prepareForImageViewScaling];
[UIView animateWithDuration:0.5 animations:^{
[self zoomWithScale:scale];
} completion:^(BOOL finished) {
if (scale == 1) {
[self clear];
}
}];
}
- (void)zoomWithScale:(CGFloat)scale
{
_totalScale = scale;
_zoomingScrollImageView.transform = CGAffineTransformMakeScale(scale, scale);
if (scale > 1) {
CGFloat contentW = _zoomingScrollImageView.frame.size.width;
CGFloat contentH = MAX(_zoomingScrollImageView.frame.size.height, self.frame.size.height);
_zoomingScrollImageView.center = CGPointMake(contentW * 0.5, contentH * 0.5);
_zoomingScrollView.contentSize = CGSizeMake(contentW, contentH);
CGPoint offset = _zoomingScrollView.contentOffset;
offset.x = (contentW - _zoomingScrollView.frame.size.width) * 0.5;
_zoomingScrollView.contentOffset = offset;
} else {
_zoomingScrollView.contentSize = _zoomingScrollImageView.frame.size;
_zoomingScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
_zoomingScrollImageView.center = _zoomingScrollView.center;
}
}
主要代码就是上面的,具体实现也不是很复杂 就是对 frame 的控制。全部代码我都放在git上了,自取。
会用到第三方库:Masonry
,SDWebImage
详情见 Demo:SLPhotoBrowser
如果你觉得对你有用,请star!
以上仅限个人愚见,欢迎吐槽!
网友评论