// // SDPhotoBrowser.m // photobrowser // // Created by aier on 15-2-3. // Copyright (c) 2015年 aier. All rights reserved. // #import "SDPhotoBrowser.h" #import "UIImageView+WebCache.h" #import "SDBrowserImageView.h" #import #import #define iPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO) //判断是否iPhoneX #define iPhoneX_NavSafeArea ([[UIScreen mainScreen] bounds].size.height >= 812.0 ? 24 : 0) // 如果是iphoneX 顶部安全区域 24 // ============在这里方便配置样式相关设置=========== // || // || // || // \\// // \/ #import "SDPhotoBrowserConfig.h" // ============================================= @implementation SDPhotoBrowser { UIScrollView *_scrollView; BOOL _hasShowedFistView; UILabel *_indexLabel; UIButton *_saveButton; UIActivityIndicatorView *_indicatorView; BOOL _willDisappear; UIWindow *currentWindows; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = SDPhotoBrowserBackgrounColor; _isMe = NO; } return self; } - (void)didMoveToSuperview { [self setupScrollView]; [self setupToolbars]; } - (void)dealloc { [currentWindows removeObserver:self forKeyPath:@"frame"]; self.delegate = nil; } - (void)setupToolbars { // 1. 序标 UILabel *indexLabel = [[UILabel alloc] init]; indexLabel.bounds = CGRectMake(0, 0, 80, 30); indexLabel.textAlignment = NSTextAlignmentCenter; indexLabel.textColor = [UIColor whiteColor]; indexLabel.font = [UIFont boldSystemFontOfSize:20]; indexLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5]; indexLabel.layer.cornerRadius = indexLabel.bounds.size.height * 0.5; indexLabel.clipsToBounds = YES; if (self.imageCount >= 1) { indexLabel.text = [NSString stringWithFormat:@"1/%ld", (long)self.imageCount]; } _indexLabel = indexLabel; [self addSubview:indexLabel]; // 2.保存按钮 UIButton *saveButton = [[UIButton alloc] init]; [saveButton setTitle:@"保存" forState:UIControlStateNormal]; [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; saveButton.backgroundColor = [UIColor colorWithRed:0.1f green:0.1f blue:0.1f alpha:0.90f]; saveButton.layer.cornerRadius = 5; saveButton.clipsToBounds = YES; [saveButton addTarget:self action:@selector(saveImage) forControlEvents:UIControlEventTouchUpInside]; _saveButton = saveButton; [self addSubview:saveButton]; } - (void)saveImage { int index = _scrollView.contentOffset.x / _scrollView.bounds.size.width; SDBrowserImageView *currentImageView = _scrollView.subviews[index]; NSData *imageData = currentImageView.animatedImage.data; [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ if(imageData != nil){ [PHAssetCreationRequest.creationRequestForAsset addResourceWithType:PHAssetResourceTypePhoto data:imageData options:nil]; }else{ [PHAssetCreationRequest creationRequestForAssetFromImage:currentImageView.image]; } } completionHandler:^(BOOL success, NSError * _Nullable error) { //保存之后需要做的事情 dispatch_async(dispatch_get_main_queue(), ^{ // 需要在主线程执行的代码 [self saveImageFinishWithError:error]; }); }]; if (_indicatorView == nil) { _indicatorView = [[UIActivityIndicatorView alloc] init]; _indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge; _indicatorView.center = self.center; [[UIApplication sharedApplication].keyWindow addSubview:_indicatorView]; } [_indicatorView startAnimating]; } -(void)saveImageFinishWithError:(NSError *)error{ [_indicatorView stopAnimating]; UILabel *label = [[UILabel alloc] init]; label.textColor = [UIColor whiteColor]; label.backgroundColor = [UIColor colorWithRed:0.1f green:0.1f blue:0.1f alpha:0.90f]; label.layer.cornerRadius = 5; label.clipsToBounds = YES; label.bounds = CGRectMake(0, 0, 150, 30); label.center = self.center; label.textAlignment = NSTextAlignmentCenter; label.font = [UIFont boldSystemFontOfSize:17]; [[UIApplication sharedApplication].keyWindow addSubview:label]; [[UIApplication sharedApplication].keyWindow bringSubviewToFront:label]; if (error) { label.text = SDPhotoBrowserSaveImageFailText; } else { label.text = SDPhotoBrowserSaveImageSuccessText; } [label performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:1.0]; } - (void)setupScrollView { _scrollView = [[UIScrollView alloc] init]; _scrollView.delegate = self; _scrollView.showsHorizontalScrollIndicator = NO; _scrollView.showsVerticalScrollIndicator = NO; _scrollView.pagingEnabled = YES; [self addSubview:_scrollView]; for (int i = 0; i < self.imageCount; i++) { SDBrowserImageView *imageView = [[SDBrowserImageView alloc] init]; imageView.tag = i; // 单击图片 UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoClick:)]; // 双击放大图片 UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewDoubleTaped:)]; doubleTap.numberOfTapsRequired = 2; [singleTap requireGestureRecognizerToFail:doubleTap]; [imageView addGestureRecognizer:singleTap]; [imageView addGestureRecognizer:doubleTap]; [_scrollView addSubview:imageView]; } [self setupImageOfImageViewForIndex:self.currentImageIndex]; } // 加载图片 - (void)setupImageOfImageViewForIndex:(NSInteger)index { SDBrowserImageView *imageView = _scrollView.subviews[index]; self.currentImageIndex = index; if (imageView.hasLoadedImage) return; if ([self highQualityImageURLForIndex:index]) { [imageView setImageWithURL:[self highQualityImageURLForIndex:index] placeholderImage:[self placeholderImageForIndex:index]]; } else { imageView.image = [self placeholderImageForIndex:index]; } imageView.hasLoadedImage = YES; } - (void)photoClick:(UITapGestureRecognizer *)recognizer { _scrollView.hidden = YES; _willDisappear = YES; SDBrowserImageView *currentImageView = (SDBrowserImageView *)recognizer.view; NSInteger currentIndex = currentImageView.tag; if (self.isHaveUserAdd) { currentIndex = currentImageView.tag + 1; } UIView *sourceView = nil; if ([self.sourceImagesContainerView isKindOfClass:UICollectionView.class]) { UICollectionView *view = (UICollectionView *)self.sourceImagesContainerView; NSIndexPath *path = [NSIndexPath indexPathForItem:currentIndex inSection:0]; sourceView = [view cellForItemAtIndexPath:path]; }else { if (self.currentImageIndex margin || (x - index * self.bounds.size.width) < - margin) { SDBrowserImageView *imageView = _scrollView.subviews[index]; if (imageView.isScaled) { [UIView animateWithDuration:0.5 animations:^{ imageView.transform = CGAffineTransformIdentity; } completion:^(BOOL finished) { [imageView eliminateScale]; }]; } } if (!_willDisappear) { if (self.isMe) { if (self.isHaveUserAdd) { _indexLabel.text = [NSString stringWithFormat:@"%d/%ld", index + 1, (long)self.imageCount]; } else { _indexLabel.text = [NSString stringWithFormat:@"%d/%ld", index, (long)self.imageCount]; } }else{ _indexLabel.text = [NSString stringWithFormat:@"%d/%ld", index + 1, (long)self.imageCount]; } } [self setupImageOfImageViewForIndex:index]; } @end