HUPhotoBrowser.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. //
  2. // HUPhotoBrowser.m
  3. // HUPhotoBrowser
  4. //
  5. // Created by mac on 16/2/24.
  6. // Copyright (c) 2016年 jinhuadiqigan. All rights reserved.
  7. //
  8. #import "HUPhotoBrowser.h"
  9. #import "HUPhotoBrowserCell.h"
  10. #import "hu_const.h"
  11. #import "HUWebImage.h"
  12. #import <SVProgressHUD/SVProgressHUD.h>
  13. @interface HUPhotoBrowser () <UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout> {
  14. CGRect _endTempFrame;
  15. NSInteger _currentPage;
  16. NSIndexPath *_zoomingIndexPath;
  17. BOOL _imageDidLoaded;
  18. BOOL _animationCompleted;
  19. }
  20. @property (nonatomic, strong) UIImageView *imageView;
  21. @property (nonatomic, strong) UIImageView *tmpImageView;
  22. @property (nonatomic, strong) UICollectionView *collectionView;
  23. @property (nonatomic, strong) UIView *toolBar;
  24. @property (nonatomic, weak) UILabel *countLab;
  25. @property (nonatomic, strong) NSArray *URLStrings;
  26. @property (nonatomic) NSInteger index;
  27. @property (nonatomic) NSInteger imagesCount;
  28. @property (nonatomic, copy) DismissBlock dismissDlock;
  29. @property (nonatomic, strong) NSArray *images;
  30. @end
  31. @implementation HUPhotoBrowser
  32. - (void)dealloc {
  33. self.collectionView.delegate = nil;
  34. [[NSNotificationCenter defaultCenter] removeObserver:self];
  35. }
  36. + (instancetype)showFromImageView:(UIImageView *)imageView withURLStrings:(NSArray *)URLStrings placeholderImage:(UIImage *)image atIndex:(NSInteger)index dismiss:(DismissBlock)block {
  37. HUPhotoBrowser *browser = [[HUPhotoBrowser alloc] initWithFrame:kScreenRect];
  38. browser.imageView = imageView;
  39. browser.URLStrings = URLStrings;
  40. browser.imagesCount = URLStrings.count;
  41. [browser resetCountLabWithIndex:index+1];
  42. [browser configureBrowser];
  43. [browser animateImageViewAtIndex:index];
  44. browser.placeholderImage = image;
  45. browser.dismissDlock = block;
  46. return browser;
  47. }
  48. + (instancetype)showFromImageView:(UIImageView *)imageView withImages:(NSArray *)images atIndex:(NSInteger)index dismiss:(DismissBlock)block {
  49. HUPhotoBrowser *browser = [[HUPhotoBrowser alloc] initWithFrame:kScreenRect];
  50. browser.imageView = imageView;
  51. browser.images = images;
  52. browser.imagesCount = images.count;
  53. [browser resetCountLabWithIndex:index+1];
  54. [browser configureBrowser];
  55. [browser animateImageViewAtIndex:index];
  56. browser.dismissDlock = block;
  57. return browser;
  58. }
  59. + (instancetype)showFromImageView:(UIImageView *)imageView withURLStrings:(NSArray *)URLStrings atIndex:(NSInteger)index {
  60. return [self showFromImageView:imageView withURLStrings:URLStrings placeholderImage:nil atIndex:index dismiss:nil];
  61. }
  62. + (instancetype)showFromImageView:(UIImageView *)imageView withImages:(NSArray *)images atIndex:(NSInteger)index {
  63. return [self showFromImageView:imageView withImages:images atIndex:index dismiss:nil];
  64. }
  65. - (instancetype)initWithFrame:(CGRect)frame {
  66. self = [super initWithFrame:frame];
  67. if (self) {
  68. self.backgroundColor = [UIColor blackColor];
  69. [self addSubview:self.collectionView];
  70. [self setupToolBar];
  71. [[NSNotificationCenter defaultCenter] removeObserver:self];
  72. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadForScreenRotate) name:UIDeviceOrientationDidChangeNotification object:nil];
  73. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(photoCellDidZooming:) name:kPhotoCellDidZommingNotification object:nil];
  74. }
  75. return self;
  76. }
  77. #pragma mark - UICollectionViewDataSource
  78. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  79. NSInteger count = 0;
  80. if (self.URLStrings) {
  81. count = _URLStrings.count;
  82. }else if (self.images) {
  83. count = _images.count;
  84. }
  85. return count;
  86. }
  87. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  88. HUPhotoBrowserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kPhotoBrowserCellID forIndexPath:indexPath];
  89. cell.indexPath = indexPath;
  90. [cell resetZoomingScale];
  91. __weak __typeof(self) wself = self;
  92. cell.tapActionBlock = ^(UITapGestureRecognizer *sender) {
  93. [wself dismiss];
  94. };
  95. if (self.URLStrings) {
  96. [cell startAnimating];
  97. __weak __typeof(cell) weakCell = cell;
  98. NSURL *url = [NSURL URLWithString:self.URLStrings[indexPath.row]];
  99. if (indexPath.row != _index) {
  100. if (_placeholderImage) {
  101. [cell stopAnimating];
  102. [cell.imageView hu_setImageWithURL:url placeholderImage:_placeholderImage completed:^(UIImage * _Nullable image, NSError * _Nullable error, NSURL * _Nullable imageUrl) {
  103. __strong __typeof(weakCell) strongCell = weakCell;
  104. [strongCell resizeImageView];
  105. }];
  106. } else {
  107. [cell.imageView hu_setImageWithURL:url placeholderImage:nil completed:^(UIImage * _Nullable image, NSError * _Nullable error, NSURL * _Nullable imageUrl) {
  108. if (image) {
  109. __strong __typeof(weakCell) strongCell = weakCell;
  110. [strongCell resizeImageView];
  111. [strongCell stopAnimating];
  112. }
  113. }];
  114. }
  115. } else {
  116. UIImage *placeHolder = _tmpImageView.image;
  117. [cell.imageView hu_setImageWithURL:url placeholderImage:placeHolder completed:^(UIImage *image, NSError *error, NSURL *imageUrl) {
  118. __strong __typeof(wself) strongSelf = wself;
  119. __strong __typeof(weakCell) strongCell = weakCell;
  120. [strongCell stopAnimating];
  121. [strongCell resizeImageView];
  122. if (!strongSelf->_imageDidLoaded) {
  123. strongSelf->_imageDidLoaded = YES;
  124. if (strongSelf->_animationCompleted) {
  125. strongSelf.collectionView.hidden = NO;
  126. [strongSelf->_tmpImageView removeFromSuperview];
  127. strongSelf->_animationCompleted = NO;
  128. }
  129. }
  130. }];
  131. }
  132. }
  133. else if (self.images) {
  134. [cell stopAnimating];
  135. cell.imageView.image = self.images[indexPath.row];
  136. [cell resizeImageView];
  137. }
  138. return cell;
  139. }
  140. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
  141. return kScreenRect.size;
  142. }
  143. - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
  144. _currentPage = scrollView.contentOffset.x/kScreenWidth + 0.5;
  145. _countLab.text = [NSString stringWithFormat:@"%zd/%zd",_currentPage+1,_imagesCount];
  146. if (_zoomingIndexPath) {
  147. [self.collectionView reloadItemsAtIndexPaths:@[_zoomingIndexPath]];
  148. _zoomingIndexPath = nil;
  149. }
  150. }
  151. #pragma mark - notification handler
  152. - (void)reloadForScreenRotate {
  153. _collectionView.frame = kScreenRect;
  154. [self.collectionView reloadData];
  155. self.collectionView.contentOffset = CGPointMake(kScreenWidth * _currentPage,0);
  156. }
  157. - (void)photoCellDidZooming:(NSNotification *)nofit {
  158. NSIndexPath *indexPath = nofit.object;
  159. _zoomingIndexPath = indexPath;
  160. }
  161. #pragma mark - getter & setter
  162. - (void)setDidHideToolBar:(BOOL)didHideToolBar {
  163. _didHideToolBar = didHideToolBar;
  164. _toolBar.hidden = didHideToolBar;
  165. }
  166. - (UICollectionView *)collectionView {
  167. if (!_collectionView) {
  168. UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
  169. layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
  170. layout.minimumInteritemSpacing = 0;
  171. layout.minimumLineSpacing = 0;
  172. _collectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:layout];
  173. _collectionView.hidden = YES;
  174. _collectionView.pagingEnabled = YES;
  175. _collectionView.showsHorizontalScrollIndicator = NO;
  176. }
  177. return _collectionView;
  178. }
  179. #pragma mark - private
  180. - (void)configureBrowser {
  181. self.collectionView.delegate = self;
  182. self.collectionView.dataSource = self;
  183. [self.collectionView registerClass:[HUPhotoBrowserCell class] forCellWithReuseIdentifier:kPhotoBrowserCellID];
  184. [[UIApplication sharedApplication].keyWindow addSubview:self];
  185. }
  186. - (void)setupToolBar {
  187. _toolBar = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height-38, self.frame.size.width, 30)];
  188. _toolBar.backgroundColor = [UIColor clearColor];
  189. [self addSubview:_toolBar];
  190. UILabel *countLab = [[UILabel alloc] init];
  191. countLab.textColor = [UIColor whiteColor];
  192. countLab.layer.cornerRadius = 2;
  193. countLab.layer.masksToBounds = YES;
  194. countLab.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
  195. countLab.font = [UIFont systemFontOfSize:13];
  196. countLab.textAlignment = NSTextAlignmentCenter;
  197. [_toolBar addSubview:countLab];
  198. _countLab = countLab;
  199. UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  200. saveBtn.frame = CGRectMake(_toolBar.frame.size.width-58, 1, 50, 28);
  201. saveBtn.layer.cornerRadius = 2;
  202. [saveBtn setBackgroundColor:[[UIColor blackColor]colorWithAlphaComponent:0.4]];
  203. [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
  204. [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  205. saveBtn.titleLabel.font = [UIFont systemFontOfSize:13];
  206. [saveBtn addTarget:self action:@selector(saveImae) forControlEvents:UIControlEventTouchUpInside];
  207. [_toolBar addSubview:saveBtn];
  208. _saveButton = saveBtn;
  209. }
  210. - (void)animateImageViewAtIndex:(NSInteger)index {
  211. _index = index;
  212. CGRect startFrame = [self.imageView.superview convertRect:self.imageView.frame toView:[UIApplication sharedApplication].keyWindow];
  213. CGRect endFrame = kScreenRect;
  214. if (self.imageView.image) {
  215. UIImage *image = self.imageView.image;
  216. CGFloat ratio = image.size.width / image.size.height;
  217. if (ratio > kScreenRatio) {
  218. endFrame.size.width = kScreenWidth;
  219. endFrame.size.height = kScreenWidth / ratio;
  220. } else {
  221. endFrame.size.height = kScreenHeight;
  222. endFrame.size.width = kScreenHeight * ratio;
  223. }
  224. endFrame.origin.x = (kScreenWidth - endFrame.size.width) / 2;
  225. endFrame.origin.y = (kScreenHeight - endFrame.size.height) / 2;
  226. }
  227. _endTempFrame = endFrame;
  228. #if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_9_0
  229. [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
  230. #endif
  231. UIImageView *tempImageView = [[UIImageView alloc] initWithFrame:startFrame];
  232. tempImageView.image = self.imageView.image;
  233. tempImageView.contentMode = UIViewContentModeScaleAspectFit;
  234. [[UIApplication sharedApplication].keyWindow addSubview:tempImageView];
  235. _tmpImageView = tempImageView;
  236. if (self.URLStrings && !self.images) {
  237. NSString *key = [HUWebImageDownloader cacheKeyForURL:[NSURL URLWithString:self.URLStrings[_index]]];
  238. UIImage *image = [HUWebImageDownloader imageFromDiskCacheForKey:key];
  239. _imageDidLoaded = image != nil;
  240. }
  241. [self.collectionView setContentOffset:CGPointMake(kScreenWidth * index,0) animated:NO];
  242. [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
  243. tempImageView.frame = endFrame;
  244. } completion:^(BOOL finished) {
  245. _currentPage = index;
  246. _animationCompleted = YES;
  247. if (self.images || _imageDidLoaded || (self.URLStrings && !_imageDidLoaded)) {
  248. self.collectionView.hidden = NO;
  249. [tempImageView removeFromSuperview];
  250. _animationCompleted = NO;
  251. }
  252. }];
  253. }
  254. - (void)dismiss {
  255. #if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_9_0
  256. [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
  257. #endif
  258. if (self.dismissDlock) {
  259. HUPhotoBrowserCell *cell = (HUPhotoBrowserCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_currentPage inSection:0]];
  260. self.dismissDlock(cell.imageView.image, _currentPage);
  261. }
  262. if (_currentPage != _index) {
  263. [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
  264. self.alpha = 0;
  265. } completion:^(BOOL finished) {
  266. [self removeFromSuperview];
  267. }];
  268. return;
  269. }
  270. CGRect endFrame = [self.imageView.superview convertRect:self.imageView.frame toView:[UIApplication sharedApplication].keyWindow];
  271. UIImageView *tempImageView = [[UIImageView alloc] initWithFrame:_endTempFrame];
  272. tempImageView.image = self.imageView.image;
  273. tempImageView.contentMode = UIViewContentModeScaleAspectFit;
  274. self.collectionView.hidden = YES;
  275. [[UIApplication sharedApplication].keyWindow addSubview:tempImageView];
  276. [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
  277. tempImageView.frame = endFrame;
  278. self.alpha = 0;
  279. } completion:^(BOOL finished) {
  280. [self removeFromSuperview];
  281. [tempImageView removeFromSuperview];
  282. }];
  283. }
  284. - (void)resetCountLabWithIndex:(NSInteger)index {
  285. NSString *text = [NSString stringWithFormat:@"%zd%zd",_imagesCount,_imagesCount];
  286. CGFloat width = [text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}].width+8;
  287. _countLab.frame = CGRectMake(8, 1, MAX(50, width), 28);
  288. _countLab.text = [NSString stringWithFormat:@"%zd/%zd",index,_imagesCount];
  289. }
  290. - (void)saveImae {
  291. HUPhotoBrowserCell *cell = (HUPhotoBrowserCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_currentPage inSection:0]];
  292. UIImage *seavedImage = cell.imageView.image;
  293. if (seavedImage) {
  294. UIImageWriteToSavedPhotosAlbum(seavedImage, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
  295. }
  296. }
  297. - (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
  298. NSString *msg = nil ;
  299. if(error != nil){
  300. msg = @"保存图片失败";
  301. [SVProgressHUD showInfoWithStatus:msg];
  302. }
  303. else{
  304. msg = @"保存图片成功";
  305. [SVProgressHUD showSuccessWithStatus:msg];
  306. }
  307. }
  308. @end