寫在之前:以下分享的內容有部分是參考網上開源代碼。
廢話不多說,直接看效果:
這個gif居然要控制在5M內,蛋疼- - 。
看完效果,如果你敢興趣的話,就可以往下看。
代碼分析:
整體可以分為三個模塊:
SLPhotoContainerView
它就是顯示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!
以上僅限個人愚見,歡迎吐槽!