├── .DS_Store ├── 3DSource ├── .DS_Store ├── JFImagePickerController │ ├── JFAssetHelper.h │ ├── JFAssetHelper.m │ ├── JFImageCollectionViewController.h │ ├── JFImageCollectionViewController.m │ ├── JFImageGroupTableViewController.h │ ├── JFImageGroupTableViewController.m │ ├── JFImageManager.h │ ├── JFImageManager.m │ ├── JFImagePickerController.h │ ├── JFImagePickerController.m │ ├── JFImagePickerViewCell.h │ ├── JFImagePickerViewCell.m │ ├── JFPhotoBrowserViewController.h │ ├── JFPhotoBrowserViewController.m │ ├── JFPhotoView.h │ └── JFPhotoView.m ├── SDWebImage │ ├── NSData+ImageContentType.h │ ├── NSData+ImageContentType.m │ ├── SDImageCache.h │ ├── SDImageCache.m │ ├── SDWebImageCompat.h │ ├── SDWebImageCompat.m │ ├── SDWebImageDecoder.h │ ├── SDWebImageDecoder.m │ ├── SDWebImageDownloader.h │ ├── SDWebImageDownloader.m │ ├── SDWebImageDownloaderOperation.h │ ├── SDWebImageDownloaderOperation.m │ ├── SDWebImageManager.h │ ├── SDWebImageManager.m │ ├── SDWebImageOperation.h │ ├── SDWebImagePrefetcher.h │ ├── SDWebImagePrefetcher.m │ ├── UIButton+WebCache.h │ ├── UIButton+WebCache.m │ ├── UIImage+GIF.h │ ├── UIImage+GIF.m │ ├── UIImage+MultiFormat.h │ ├── UIImage+MultiFormat.m │ ├── UIImageView+HighlightedWebCache.h │ ├── UIImageView+HighlightedWebCache.m │ ├── UIImageView+WebCache.h │ ├── UIImageView+WebCache.m │ ├── UIView+WebCacheOperation.h │ └── UIView+WebCacheOperation.m └── WSImagebroswerVC │ ├── WSImageBroserCell.h │ ├── WSImageBroserCell.m │ ├── WSImageBroswerVC.h │ ├── WSImageBroswerVC.m │ ├── WSImageModel.h │ ├── WSImageModel.m │ ├── WSPhotosBroseVC.h │ └── WSPhotosBroseVC.m ├── README.md ├── WSImagePicker.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ ├── xcshareddata │ │ └── WSImagePicker.xcscmblueprint │ └── xcuserdata │ │ └── wsjtwzs.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ └── wsjtwzs.xcuserdatad │ ├── xcdebugger │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ ├── WSImagePicker.xcscheme │ └── xcschememanagement.plist └── WSImagePicker ├── .DS_Store ├── AppDelegate.h ├── AppDelegate.m ├── Assets.xcassets ├── AppIcon.appiconset │ └── Contents.json ├── Contents.json └── bg │ ├── Contents.json │ └── bg_photo_add.imageset │ ├── Contents.json │ └── 转售-添加图片.png ├── Base.lproj ├── LaunchScreen.storyboard └── Main.storyboard ├── Info.plist ├── ViewController.h ├── ViewController.m ├── WSImagePicker ├── WSImagePickerView.h └── WSImagePickerView.m └── main.m /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wsjtwzs/WSImagePicker/a8928871444ac19d0155ba574dd3dcee13d816cc/.DS_Store -------------------------------------------------------------------------------- /3DSource/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wsjtwzs/WSImagePicker/a8928871444ac19d0155ba574dd3dcee13d816cc/3DSource/.DS_Store -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFAssetHelper.h: -------------------------------------------------------------------------------- 1 | // 2 | // AssetHelper.m 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | #define APP_COLOR [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0] 12 | 13 | #define ASSETHELPER [JFAssetHelper sharedAssetHelper] 14 | 15 | #define ASSET_PHOTO_THUMBNAIL 0 16 | #define ASSET_PHOTO_ASPECT_THUMBNAIL 1 17 | #define ASSET_PHOTO_SCREEN_SIZE 2 18 | #define ASSET_PHOTO_FULL_RESOLUTION 3 19 | 20 | @interface JFAssetHelper : NSObject 21 | 22 | - (void)initAsset; 23 | 24 | @property (nonatomic, strong) ALAssetsLibrary *assetsLibrary; 25 | @property (nonatomic, strong) NSMutableArray *assetPhotos; 26 | @property (nonatomic, strong) NSMutableArray *assetGroups; 27 | @property (nonatomic) NSInteger currentGroupIndex; 28 | @property (nonatomic) NSInteger previewIndex; 29 | @property (readwrite) BOOL bReverse; 30 | @property (nonatomic, strong) NSMutableArray *selectdPhotos; 31 | @property (nonatomic, strong) NSMutableArray *selectdAssets; 32 | @property (nonatomic, strong) NSMutableArray *defaultAssets; 33 | @property (nonatomic, strong) NSString *originStr; 34 | @property (nonatomic, strong) ALAsset *selectdAsset; 35 | @property (nonatomic, assign) NSInteger maxCount; 36 | 37 | + (JFAssetHelper *)sharedAssetHelper; 38 | 39 | // get album list from asset 40 | - (void)getGroupList:(void (^)(NSArray *))result; 41 | // get photos from specific album with ALAssetsGroup object 42 | - (void)getPhotoListOfGroup:(ALAssetsGroup *)alGroup result:(void (^)(NSArray *))result; 43 | // get photos from specific album with index of album array 44 | - (void)getPhotoListOfGroupByIndex:(NSInteger)nGroupIndex result:(void (^)(NSArray *))result; 45 | // get photos from camera roll 46 | - (void)getSavedPhotoList:(void (^)(NSArray *))result error:(void (^)(NSError *))error; 47 | 48 | - (NSInteger)getGroupCount; 49 | - (NSInteger)getPhotoCountOfCurrentGroup; 50 | - (NSDictionary *)getGroupInfo:(NSInteger)nIndex; 51 | 52 | - (void)clearData; 53 | 54 | // utils 55 | - (UIImage *)getCroppedImage:(NSURL *)urlImage; 56 | - (UIImage *)getImageFromAsset:(ALAsset *)asset type:(NSInteger)nType; 57 | - (UIImage *)getImageAtIndex:(NSInteger)nIndex type:(NSInteger)nType; 58 | - (ALAsset *)getAssetAtIndex:(NSInteger)nIndex; 59 | - (ALAssetsGroup *)getGroupAtIndex:(NSInteger)nIndex; 60 | 61 | @end 62 | 63 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFAssetHelper.m: -------------------------------------------------------------------------------- 1 | // 2 | // AssetHelper.m 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import "JFAssetHelper.h" 10 | 11 | @implementation JFAssetHelper 12 | 13 | 14 | + (JFAssetHelper *)sharedAssetHelper 15 | { 16 | static JFAssetHelper *_sharedInstance = nil; 17 | static dispatch_once_t onceToken; 18 | dispatch_once(&onceToken, ^{ 19 | _sharedInstance = [[JFAssetHelper alloc] init]; 20 | [_sharedInstance initAsset]; 21 | }); 22 | 23 | return _sharedInstance; 24 | } 25 | 26 | - (void)initAsset 27 | { 28 | if (_selectdPhotos==nil) { 29 | _selectdPhotos = [[NSMutableArray alloc] init]; 30 | _selectdAssets = [[NSMutableArray alloc] init]; 31 | } 32 | if (self.assetsLibrary == nil) 33 | { 34 | _assetsLibrary = [[ALAssetsLibrary alloc] init]; 35 | 36 | NSString *strVersion = [[UIDevice alloc] systemVersion]; 37 | if ([strVersion compare:@"5"] >= 0) 38 | [_assetsLibrary writeImageToSavedPhotosAlbum:nil metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) { 39 | }]; 40 | } 41 | } 42 | 43 | - (void)setCameraRollAtFirst 44 | { 45 | for (ALAssetsGroup *group in _assetGroups) 46 | { 47 | if ([[group valueForProperty:@"ALAssetsGroupPropertyType"] intValue] == ALAssetsGroupSavedPhotos) 48 | { 49 | // send to head 50 | [_assetGroups removeObject:group]; 51 | [_assetGroups insertObject:group atIndex:0]; 52 | 53 | return; 54 | } 55 | } 56 | } 57 | 58 | - (void)getGroupList:(void (^)(NSArray *))result 59 | { 60 | [self initAsset]; 61 | 62 | void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) 63 | { 64 | [group setAssetsFilter:[ALAssetsFilter allPhotos]]; 65 | 66 | if (group == nil) 67 | { 68 | if (_bReverse) 69 | _assetGroups = [[NSMutableArray alloc] initWithArray:[[_assetGroups reverseObjectEnumerator] allObjects]]; 70 | 71 | [self setCameraRollAtFirst]; 72 | 73 | // end of enumeration 74 | result(_assetGroups); 75 | return; 76 | } 77 | 78 | [_assetGroups addObject:group]; 79 | }; 80 | 81 | void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) 82 | { 83 | NSLog(@"Error : %@", [error description]); 84 | }; 85 | 86 | _assetGroups = [[NSMutableArray alloc] init]; 87 | [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll 88 | usingBlock:assetGroupEnumerator 89 | failureBlock:assetGroupEnumberatorFailure]; 90 | } 91 | 92 | - (void)getPhotoListOfGroup:(ALAssetsGroup *)alGroup result:(void (^)(NSArray *))result 93 | { 94 | [self initAsset]; 95 | 96 | _assetPhotos = [[NSMutableArray alloc] init]; 97 | [alGroup setAssetsFilter:[ALAssetsFilter allPhotos]]; 98 | [alGroup enumerateAssetsUsingBlock:^(ALAsset *alPhoto, NSUInteger index, BOOL *stop) { 99 | 100 | if(alPhoto == nil) 101 | { 102 | if (_bReverse) { 103 | if (_defaultAssets) { 104 | [_assetPhotos addObjectsFromArray:_defaultAssets]; 105 | } 106 | 107 | [_defaultAssets addObject:@"camera"]; 108 | 109 | _assetPhotos = [[NSMutableArray alloc] initWithArray:[[_assetPhotos reverseObjectEnumerator] allObjects]]; 110 | } 111 | 112 | result(_assetPhotos); 113 | return; 114 | } 115 | 116 | [_assetPhotos addObject:alPhoto]; 117 | }]; 118 | } 119 | 120 | - (void)getPhotoListOfGroupByIndex:(NSInteger)nGroupIndex result:(void (^)(NSArray *))result 121 | { 122 | [self getPhotoListOfGroup:_assetGroups[nGroupIndex] result:^(NSArray *aResult) { 123 | 124 | result(_assetPhotos); 125 | 126 | }]; 127 | } 128 | 129 | - (void)getSavedPhotoList:(void (^)(NSArray *))result error:(void (^)(NSError *))error 130 | { 131 | [self initAsset]; 132 | 133 | dispatch_async(dispatch_get_main_queue(), ^{ 134 | 135 | void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) 136 | { 137 | if ([[group valueForProperty:@"ALAssetsGroupPropertyType"] intValue] == ALAssetsGroupSavedPhotos) 138 | { 139 | [group setAssetsFilter:[ALAssetsFilter allPhotos]]; 140 | 141 | [group enumerateAssetsUsingBlock:^(ALAsset *alPhoto, NSUInteger index, BOOL *stop) { 142 | 143 | if(alPhoto == nil) 144 | { 145 | if (_bReverse) 146 | _assetPhotos = [[NSMutableArray alloc] initWithArray:[[_assetPhotos reverseObjectEnumerator] allObjects]]; 147 | 148 | result(_assetPhotos); 149 | return; 150 | } 151 | 152 | [_assetPhotos addObject:alPhoto]; 153 | }]; 154 | } 155 | }; 156 | 157 | void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *err) 158 | { 159 | NSLog(@"Error : %@", [err description]); 160 | error(err); 161 | }; 162 | 163 | _assetPhotos = [[NSMutableArray alloc] init]; 164 | [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos 165 | usingBlock:assetGroupEnumerator 166 | failureBlock:assetGroupEnumberatorFailure]; 167 | }); 168 | } 169 | 170 | - (NSInteger)getGroupCount 171 | { 172 | return _assetGroups.count; 173 | } 174 | 175 | - (NSInteger)getPhotoCountOfCurrentGroup 176 | { 177 | return _assetPhotos.count; 178 | } 179 | 180 | - (NSDictionary *)getGroupInfo:(NSInteger)nIndex 181 | { 182 | return @{@"name" : [_assetGroups[nIndex] valueForProperty:ALAssetsGroupPropertyName], 183 | @"count" : @([_assetGroups[nIndex] numberOfAssets])}; 184 | } 185 | 186 | - (void)clearData 187 | { 188 | [_selectdAssets removeAllObjects]; 189 | _selectdAssets = nil; 190 | [_selectdPhotos removeAllObjects]; 191 | _selectdPhotos = nil; 192 | [_defaultAssets removeAllObjects]; 193 | _defaultAssets = nil; 194 | _assetGroups = nil; 195 | _assetPhotos = nil; 196 | } 197 | 198 | - (NSMutableArray *)defaultAssets{ 199 | if (_defaultAssets==nil) { 200 | _defaultAssets = [[NSMutableArray alloc] init]; 201 | } 202 | return _defaultAssets; 203 | } 204 | 205 | - (NSMutableArray *)selectdAssets{ 206 | if (_selectdAssets==nil) { 207 | _selectdAssets = [[NSMutableArray alloc] init]; 208 | } 209 | return _selectdAssets; 210 | } 211 | 212 | - (NSMutableArray *)selectdPhotos{ 213 | if (_selectdPhotos==nil) { 214 | _selectdPhotos = [[NSMutableArray alloc] init]; 215 | } 216 | return _selectdPhotos; 217 | } 218 | 219 | #pragma mark - utils 220 | - (UIImage *)getCroppedImage:(NSURL *)urlImage 221 | { 222 | __block UIImage *iImage = nil; 223 | __block BOOL bBusy = YES; 224 | 225 | ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) 226 | { 227 | ALAssetRepresentation *rep = [myasset defaultRepresentation]; 228 | NSString *strXMP = rep.metadata[@"AdjustmentXMP"]; 229 | if (strXMP == nil || [strXMP isKindOfClass:[NSNull class]]) 230 | { 231 | CGImageRef iref = [rep fullResolutionImage]; 232 | if (iref) 233 | iImage = [UIImage imageWithCGImage:iref scale:1.0 orientation:(UIImageOrientation)rep.orientation]; 234 | else 235 | iImage = nil; 236 | } 237 | else 238 | { 239 | // to get edited photo by photo app 240 | NSData *dXMP = [strXMP dataUsingEncoding:NSUTF8StringEncoding]; 241 | 242 | CIImage *image = [CIImage imageWithCGImage:rep.fullResolutionImage]; 243 | 244 | NSError *error = nil; 245 | NSArray *filterArray = [CIFilter filterArrayFromSerializedXMP:dXMP 246 | inputImageExtent:image.extent 247 | error:&error]; 248 | if (error) { 249 | NSLog(@"Error during CIFilter creation: %@", [error localizedDescription]); 250 | } 251 | 252 | for (CIFilter *filter in filterArray) { 253 | [filter setValue:image forKey:kCIInputImageKey]; 254 | image = [filter outputImage]; 255 | } 256 | 257 | iImage = [UIImage imageWithCIImage:image scale:1.0 orientation:(UIImageOrientation)rep.orientation]; 258 | } 259 | 260 | bBusy = NO; 261 | }; 262 | 263 | ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror) 264 | { 265 | NSLog(@"booya, cant get image - %@",[myerror localizedDescription]); 266 | }; 267 | 268 | [_assetsLibrary assetForURL:urlImage 269 | resultBlock:resultblock 270 | failureBlock:failureblock]; 271 | 272 | while (bBusy) 273 | [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; 274 | 275 | return iImage; 276 | } 277 | 278 | - (UIImage *)getImageFromAsset:(ALAsset *)asset type:(NSInteger)nType 279 | { 280 | CGImageRef iRef = nil; 281 | 282 | if (nType == ASSET_PHOTO_THUMBNAIL) 283 | iRef = [asset thumbnail]; 284 | else if (nType == ASSET_PHOTO_ASPECT_THUMBNAIL) 285 | iRef = [asset aspectRatioThumbnail]; 286 | else if (nType == ASSET_PHOTO_SCREEN_SIZE) 287 | iRef = [asset.defaultRepresentation fullScreenImage]; 288 | else if (nType == ASSET_PHOTO_FULL_RESOLUTION) 289 | { 290 | NSString *strXMP = asset.defaultRepresentation.metadata[@"AdjustmentXMP"]; 291 | if (strXMP == nil || [strXMP isKindOfClass:[NSNull class]]) 292 | { 293 | iRef = [asset.defaultRepresentation fullResolutionImage]; 294 | return [UIImage imageWithCGImage:iRef scale:1.0 orientation:(UIImageOrientation)asset.defaultRepresentation.orientation]; 295 | } 296 | else 297 | { 298 | NSData *dXMP = [strXMP dataUsingEncoding:NSUTF8StringEncoding]; 299 | 300 | CIImage *image = [CIImage imageWithCGImage:asset.defaultRepresentation.fullResolutionImage]; 301 | 302 | NSError *error = nil; 303 | NSArray *filterArray = [CIFilter filterArrayFromSerializedXMP:dXMP 304 | inputImageExtent:image.extent 305 | error:&error]; 306 | if (error) { 307 | NSLog(@"Error during CIFilter creation: %@", [error localizedDescription]); 308 | } 309 | 310 | for (CIFilter *filter in filterArray) { 311 | [filter setValue:image forKey:kCIInputImageKey]; 312 | image = [filter outputImage]; 313 | } 314 | CIContext *context = [CIContext contextWithOptions:nil]; 315 | CGImageRef cgimage = [context createCGImage:image fromRect:[image extent]]; 316 | UIImage *iImage = [UIImage imageWithCGImage:cgimage scale:1.0 orientation:(UIImageOrientation)asset.defaultRepresentation.orientation]; 317 | return iImage; 318 | } 319 | } 320 | return [UIImage imageWithCGImage:iRef]; 321 | } 322 | 323 | - (UIImage *)getImageAtIndex:(NSInteger)nIndex type:(NSInteger)nType 324 | { 325 | return [self getImageFromAsset:(ALAsset *)_assetPhotos[nIndex] type:nType]; 326 | } 327 | 328 | - (ALAsset *)getAssetAtIndex:(NSInteger)nIndex 329 | { 330 | return _assetPhotos[nIndex]; 331 | } 332 | 333 | - (ALAssetsGroup *)getGroupAtIndex:(NSInteger)nIndex 334 | { 335 | return _assetGroups[nIndex]; 336 | } 337 | 338 | @end 339 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFImageCollectionViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // JFImageCollectionViewController.h 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2014年 Johnil. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface JFImageCollectionViewController : UIViewController 12 | 13 | - (UICollectionView *)collectionView; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFImageCollectionViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // JFImageCollectionViewController.m 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import "JFImageCollectionViewController.h" 10 | #import "JFImagePickerViewCell.h" 11 | #import "JFPhotoBrowserViewController.h" 12 | #import "JFImagePickerController.h" 13 | #import "JFAssetHelper.h" 14 | #import "JFImageManager.h" 15 | #import 16 | 17 | @interface JFImageCollectionViewController () 18 | 19 | @end 20 | 21 | @implementation JFImageCollectionViewController { 22 | UICollectionView *photosList; 23 | NSInteger currentIndex; 24 | BOOL scrollToToping; 25 | NSTimer *timer; 26 | } 27 | 28 | - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 29 | { 30 | self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 31 | if (self) { 32 | } 33 | return self; 34 | } 35 | 36 | - (void)viewWillAppear:(BOOL)animated{ 37 | // self.navigationItem.title = [[ASSETHELPER.assetGroups objectAtIndex:ASSETHELPER.currentGroupIndex] valueForProperty:ALAssetsGroupPropertyName]; 38 | // self.navigationItem.title = @"照片库"; 39 | UILabel *label = [[UILabel alloc] init]; 40 | label.textColor = [UIColor whiteColor]; 41 | label.text = @"照片库"; 42 | label.font = [UIFont systemFontOfSize:17]; 43 | [label sizeToFit]; 44 | self.navigationItem.titleView = label; 45 | [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault]; 46 | UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)]; 47 | 48 | self.navigationItem.rightBarButtonItem = cancel; 49 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showNormalPhotoBrowser:) name:@"showNormalPhotoBrowser" object:nil]; 50 | } 51 | 52 | - (void)viewWillDisappear:(BOOL)animated{ 53 | self.navigationItem.title = nil; 54 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 55 | } 56 | 57 | - (void)cancel{ 58 | [(JFImagePickerController *)self.navigationController cancel]; 59 | } 60 | 61 | - (UICollectionView *)collectionView{ 62 | return photosList; 63 | } 64 | 65 | - (void)viewDidLoad 66 | { 67 | [super viewDidLoad]; 68 | self.view.backgroundColor = [UIColor whiteColor]; 69 | UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; 70 | flowLayout.minimumInteritemSpacing = 0; 71 | flowLayout.minimumLineSpacing = 3; 72 | NSInteger size = [UIScreen mainScreen].bounds.size.width/4-1; 73 | if (size%2!=0) { 74 | size-=1; 75 | } 76 | flowLayout.itemSize = CGSizeMake(size, size); 77 | flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0); 78 | 79 | photosList = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout]; 80 | photosList.contentInset = UIEdgeInsetsMake(0, 0, 44, 0); 81 | photosList.scrollIndicatorInsets = photosList.contentInset; 82 | photosList.delegate = self; 83 | photosList.dataSource = self; 84 | photosList.backgroundColor = [UIColor whiteColor]; 85 | [self.view addSubview:photosList]; 86 | [photosList registerClass:[JFImagePickerViewCell class] forCellWithReuseIdentifier:@"imagePickerCell"]; 87 | [ASSETHELPER getPhotoListOfGroupByIndex:ASSETHELPER.currentGroupIndex result:^(NSArray *r) { 88 | [[JFImageManager sharedManager] startCahcePhotoThumbWithSize:CGSizeMake(size, size)]; 89 | [photosList reloadData]; 90 | if (ASSETHELPER.previewIndex>=0) { 91 | JFPhotoBrowserViewController *photoBrowser = [[JFPhotoBrowserViewController alloc] initWithPreview]; 92 | photoBrowser.delegate = self.navigationController; 93 | [self.navigationController pushViewController:photoBrowser animated:YES]; 94 | } 95 | 96 | for (NSDictionary *dict in ASSETHELPER.selectdPhotos) { 97 | NSArray *temp = [[[dict allKeys] firstObject] componentsSeparatedByString:@"-"]; 98 | NSInteger row = [temp[0] integerValue]; 99 | NSInteger group = [temp[1] integerValue]; 100 | if (group==ASSETHELPER.currentGroupIndex) { 101 | [photosList scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO]; 102 | break; 103 | } 104 | } 105 | }]; 106 | } 107 | 108 | - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ 109 | return 1; 110 | } 111 | 112 | - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ 113 | return [ASSETHELPER getPhotoCountOfCurrentGroup]; 114 | } 115 | 116 | - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 117 | JFImagePickerViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imagePickerCell" forIndexPath:indexPath]; 118 | cell.indexPath = indexPath; 119 | cell.tag = indexPath.item; 120 | ALAsset *asset = [ASSETHELPER getAssetAtIndex:indexPath.row]; 121 | [[JFImageManager sharedManager] thumbWithAsset:asset resultHandler:^(UIImage *result) { 122 | if (cell.tag==indexPath.item) { 123 | cell.imageView.image = result; 124 | } 125 | }]; 126 | BOOL hasItem = NO; 127 | int num = 0; 128 | for (NSDictionary *temp in ASSETHELPER.selectdPhotos) { 129 | if ([[[temp allKeys] firstObject] isEqualToString:[NSString stringWithFormat:@"%ld-%ld",(long)indexPath.row, (long)ASSETHELPER.currentGroupIndex]]) { 130 | num = [[[temp allValues] firstObject] intValue]; 131 | hasItem = YES; 132 | } 133 | } 134 | if (hasItem) { 135 | [cell selectOfNum:num]; 136 | } else { 137 | [cell selectOfNum:-1]; 138 | } 139 | return cell; 140 | } 141 | 142 | - (void)showNormalPhotoBrowser:(NSNotification *)notifi{ 143 | currentIndex = [notifi.object row]; 144 | JFPhotoBrowserViewController *photoBrowser = [[JFPhotoBrowserViewController alloc] initWithNormal]; 145 | photoBrowser.delegate = self; 146 | [self.navigationController pushViewController:photoBrowser animated:YES]; 147 | } 148 | 149 | - (NSInteger)numOfPhotosFromPhotoBrowser:(JFPhotoBrowserViewController *)browser{ 150 | return [ASSETHELPER getPhotoCountOfCurrentGroup]; 151 | } 152 | 153 | - (NSInteger)currentIndexFromPhotoBrowser:(JFPhotoBrowserViewController *)browser{ 154 | return currentIndex; 155 | } 156 | 157 | - (ALAsset *)assetWithIndex:(NSInteger)index fromPhotoBrowser:(JFPhotoBrowserViewController *)browser{ 158 | return [ASSETHELPER getAssetAtIndex:index]; 159 | } 160 | 161 | - (void)photoBrowser:(JFPhotoBrowserViewController *)browser didShowPage:(NSInteger)page{ 162 | [photosList scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:page inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO]; 163 | } 164 | 165 | - (JFImagePickerViewCell *)cellForRow:(NSInteger)row{ 166 | return (JFImagePickerViewCell *)[photosList cellForItemAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]]; 167 | } 168 | 169 | @end 170 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFImageGroupTableViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // JFImageGroupTableViewController.h 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface JFImageGroupTableViewController : UITableViewController 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFImageGroupTableViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // JFImageGroupTableViewController.m 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import "JFImageGroupTableViewController.h" 10 | #import "JFImageCollectionViewController.h" 11 | #import "JFImagePickerController.h" 12 | #import "JFAssetHelper.h" 13 | 14 | @interface JFImageGroupTableViewController () 15 | 16 | @end 17 | 18 | @implementation JFImageGroupTableViewController 19 | 20 | - (id)initWithStyle:(UITableViewStyle)style 21 | { 22 | self = [super initWithStyle:style]; 23 | if (self) { 24 | // Custom initialization 25 | } 26 | return self; 27 | } 28 | 29 | - (void)viewWillAppear:(BOOL)animated{ 30 | // self.navigationItem.title = @"相册"; 31 | UILabel *label = [[UILabel alloc] init]; 32 | label.textColor = [UIColor whiteColor]; 33 | label.text = @"相册"; 34 | label.font = [UIFont systemFontOfSize:17]; 35 | [label sizeToFit]; 36 | self.navigationItem.titleView = label; 37 | UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)]; 38 | self.navigationItem.rightBarButtonItem = cancel; 39 | } 40 | 41 | - (void)cancel{ 42 | [(JFImagePickerController *)self.navigationController cancel]; 43 | } 44 | 45 | - (void)viewDidLoad 46 | { 47 | [super viewDidLoad]; 48 | self.navigationController.navigationBar.translucent = YES; 49 | self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent; 50 | self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; 51 | self.tableView.tableFooterView = [UIView new]; 52 | ASSETHELPER.bReverse = YES; 53 | [ASSETHELPER getGroupList:^(NSArray *a) { 54 | [self.tableView reloadData]; 55 | ASSETHELPER.currentGroupIndex = 0; 56 | JFImageCollectionViewController *picker = [[JFImageCollectionViewController alloc] initWithNibName:nil bundle:nil]; 57 | [self.navigationController pushViewController:picker animated:NO]; 58 | }]; 59 | } 60 | 61 | - (void)didReceiveMemoryWarning 62 | { 63 | [super didReceiveMemoryWarning]; 64 | // Dispose of any resources that can be recreated. 65 | } 66 | 67 | #pragma mark - Table view data source 68 | 69 | - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 70 | { 71 | return 1; 72 | } 73 | 74 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 75 | { 76 | return [[JFAssetHelper sharedAssetHelper] getGroupCount]; 77 | } 78 | 79 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 80 | { 81 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier"]; 82 | if (cell==nil) { 83 | cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"reuseIdentifier"]; 84 | } 85 | ALAssetsGroup *group = [ASSETHELPER getGroupAtIndex:indexPath.row]; 86 | cell.imageView.image = [UIImage imageWithCGImage:[group posterImage]]; 87 | cell.textLabel.text = [group valueForProperty:ALAssetsGroupPropertyName]; 88 | cell.detailTextLabel.text = [NSString stringWithFormat:@"%ld", (long)[group numberOfAssets]]; 89 | cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 90 | return cell; 91 | } 92 | 93 | - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 94 | return 80; 95 | } 96 | 97 | - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 98 | [tableView deselectRowAtIndexPath:indexPath animated:YES]; 99 | ASSETHELPER.currentGroupIndex = indexPath.row; 100 | JFImageCollectionViewController *picker = [[JFImageCollectionViewController alloc] initWithNibName:nil bundle:nil]; 101 | [self.navigationController pushViewController:picker animated:YES]; 102 | } 103 | 104 | @end 105 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFImageManager.h: -------------------------------------------------------------------------------- 1 | // 2 | // JFImageManager.h 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15/7/4. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | @interface JFImageManager : NSObject 12 | 13 | + (JFImageManager *)sharedManager; 14 | - (void)clearMem; 15 | - (void)startCahcePhotoThumbWithSize:(CGSize)size; 16 | - (void)thumbWithAsset:(ALAsset *)asset 17 | resultHandler:(void (^)(UIImage *result))resultHandler; 18 | - (void)imageWithAsset:(ALAsset *)asset 19 | resultHandler:(void (^)(CGImageRef imageRef, BOOL longImage))resultHandler; 20 | 21 | @end 22 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFImageManager.m: -------------------------------------------------------------------------------- 1 | // 2 | // JFImageManager.m 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15/7/4. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import "JFImageManager.h" 10 | #import "JFAssetHelper.h" 11 | #import 12 | 13 | @implementation JFImageManager { 14 | NSCache *memCache; 15 | NSMutableDictionary *resuleHandlers; 16 | } 17 | 18 | + (JFImageManager *)sharedManager{ 19 | static JFImageManager *_sharedInstance = nil; 20 | static dispatch_once_t onceToken; 21 | dispatch_once(&onceToken, ^{ 22 | _sharedInstance = [[JFImageManager alloc] init]; 23 | }); 24 | return _sharedInstance; 25 | } 26 | 27 | - (instancetype)init{ 28 | self = [super init]; 29 | if (self) { 30 | resuleHandlers = [[NSMutableDictionary alloc] init]; 31 | memCache = [[NSCache alloc] init]; 32 | memCache.name = @"com.johnil.JFImagePickerController.caches"; 33 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(memoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; 34 | } 35 | return self; 36 | } 37 | 38 | - (void)clearMem{ 39 | [memCache removeAllObjects]; 40 | } 41 | 42 | - (void)memoryWarning{ 43 | [self clearMem]; 44 | } 45 | 46 | - (void)startCahcePhotoThumbWithSize:(CGSize)toSize{ 47 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 48 | NSArray *assets = ASSETHELPER.assetPhotos; 49 | for (ALAsset *asset in assets) { 50 | CGImageRef fullImageRef = nil; 51 | CGSize screenSize = [UIScreen mainScreen].bounds.size; 52 | screenSize.height *= [UIScreen mainScreen].scale; 53 | screenSize.width *= [UIScreen mainScreen].scale; 54 | CGSize size; 55 | CGRect partRect = CGRectZero; 56 | CGSize dimensions = asset.defaultRepresentation.dimensions; 57 | float maxPixel = 0; 58 | if (dimensions.width>dimensions.height) { 59 | if (dimensions.width/2>dimensions.height&&dimensions.width/2>screenSize.width&&dimensions.height>toSize.height*[UIScreen mainScreen].scale) { 60 | float scale = (dimensions.height/(toSize.width*[UIScreen mainScreen].scale)); 61 | if (scale<1) { 62 | maxPixel = dimensions.width; 63 | } else { 64 | maxPixel = dimensions.width/scale; 65 | } 66 | fullImageRef = [self thumbnailForAsset:asset maxPixelSize:maxPixel]; 67 | size = CGSizeMake(CGImageGetWidth(fullImageRef), CGImageGetHeight(fullImageRef)); 68 | partRect = CGRectMake(size.width/2-size.height/2, 0, size.height, size.height); 69 | } 70 | } else { 71 | if (dimensions.height/2>dimensions.width&&dimensions.height/2>screenSize.height&&dimensions.width>toSize.width*[UIScreen mainScreen].scale) { 72 | float scale = (dimensions.width/(toSize.width*[UIScreen mainScreen].scale)); 73 | if (scale<1) { 74 | maxPixel = dimensions.height; 75 | } else { 76 | maxPixel = dimensions.height/scale; 77 | } 78 | fullImageRef = [self thumbnailForAsset:asset maxPixelSize:maxPixel]; 79 | size = CGSizeMake(CGImageGetWidth(fullImageRef), CGImageGetHeight(fullImageRef)); 80 | partRect = CGRectMake(0, size.height/2-size.width/2, size.width, size.width); 81 | } 82 | } 83 | UIImage *temp; 84 | if (fullImageRef) { 85 | CGImageRef part = CGImageCreateWithImageInRect(fullImageRef, partRect); 86 | CGImageRef tempRef = [self normalizeImage:part]; 87 | temp =[UIImage imageWithCGImage:tempRef]; 88 | [memCache setObject:temp forKey:asset.defaultRepresentation.filename]; 89 | CGImageRelease(tempRef); 90 | CGImageRelease(part); 91 | tempRef = nil; 92 | part = nil; 93 | void (^resultHandler)(UIImage *result) = resuleHandlers[asset.defaultRepresentation.filename]; 94 | if (resultHandler) { 95 | [resuleHandlers removeObjectForKey:asset.defaultRepresentation.filename]; 96 | dispatch_async(dispatch_get_main_queue(), ^{ 97 | resultHandler(temp); 98 | }); 99 | } 100 | } else { 101 | [memCache setObject:@"normal" forKey:asset.defaultRepresentation.filename]; 102 | } 103 | } 104 | }); 105 | 106 | } 107 | 108 | - (void)thumbWithAsset:(ALAsset *)asset 109 | resultHandler:(void (^)(UIImage *result))resultHandler{ 110 | if (!resultHandler) { 111 | return; 112 | } 113 | UIImage *image = [UIImage imageWithCGImage:asset.thumbnail]; 114 | resultHandler(image); 115 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 116 | id thumb = [memCache objectForKey:asset.defaultRepresentation.filename]; 117 | if (thumb) { 118 | if ([thumb isKindOfClass:[UIImage class]]) { 119 | dispatch_async(dispatch_get_main_queue(), ^{ 120 | resultHandler(thumb); 121 | }); 122 | } else { 123 | UIImage *image = [UIImage imageWithCGImage:asset.aspectRatioThumbnail]; 124 | dispatch_async(dispatch_get_main_queue(), ^{ 125 | resultHandler(image); 126 | }); 127 | } 128 | } else { 129 | [resuleHandlers setValue:resultHandler forKey:asset.defaultRepresentation.filename]; 130 | } 131 | }); 132 | 133 | } 134 | 135 | - (void)imageWithAsset:(ALAsset *)asset 136 | resultHandler:(void (^)(CGImageRef imageRef, BOOL longImage))resultHandler { 137 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 138 | CGSize dimensions = asset.defaultRepresentation.dimensions; 139 | CGSize screenSize = [UIScreen mainScreen].bounds.size; 140 | float maxPixel = 0; 141 | CGImageRef fullImageRef = nil; 142 | BOOL isLong = NO; 143 | if (dimensions.width>dimensions.height) { 144 | if (dimensions.width/2>dimensions.height&&dimensions.width/2>screenSize.width*[UIScreen mainScreen].scale) { 145 | float scale = (dimensions.height/(screenSize.width*[UIScreen mainScreen].scale)); 146 | if (scale<1) { 147 | maxPixel = dimensions.width; 148 | } else { 149 | maxPixel = dimensions.width/scale; 150 | } 151 | fullImageRef = [self thumbnailForAsset:asset maxPixelSize:maxPixel]; 152 | isLong = YES; 153 | } else { 154 | fullImageRef = [asset.defaultRepresentation fullScreenImage]; 155 | } 156 | } else { 157 | if (dimensions.height/2>dimensions.width&&dimensions.height/2>screenSize.height*[UIScreen mainScreen].scale) { 158 | float scale = (dimensions.width/(screenSize.width*[UIScreen mainScreen].scale)); 159 | if (scale<1) { 160 | maxPixel = dimensions.height; 161 | } else { 162 | maxPixel = dimensions.height/scale; 163 | } 164 | fullImageRef = [self thumbnailForAsset:asset maxPixelSize:maxPixel]; 165 | isLong = YES; 166 | } else { 167 | fullImageRef = [asset.defaultRepresentation fullScreenImage]; 168 | } 169 | } 170 | resultHandler(fullImageRef, isLong); 171 | }); 172 | 173 | } 174 | 175 | - (CGImageRef)normalizeImage:(CGImageRef)imageRef{ 176 | NSInteger width = CGImageGetWidth(imageRef); 177 | NSInteger height = CGImageGetHeight(imageRef); 178 | CGRect destRect = CGRectMake(0, 0, width, height); 179 | CGColorSpaceRef genericColorSpace = CGColorSpaceCreateDeviceRGB(); 180 | CGContextRef thumbBitmapCtxt = CGBitmapContextCreate(NULL, 181 | width, 182 | height, 183 | 8, (4 * width), 184 | genericColorSpace, 185 | (CGBitmapInfo)kCGImageAlphaPremultipliedLast); 186 | CGColorSpaceRelease(genericColorSpace); 187 | CGContextSetInterpolationQuality(thumbBitmapCtxt, kCGInterpolationDefault); 188 | CGContextDrawImage(thumbBitmapCtxt, destRect, imageRef); 189 | CGImageRef tmpThumbImage = CGBitmapContextCreateImage(thumbBitmapCtxt); 190 | CGContextRelease(thumbBitmapCtxt); 191 | return tmpThumbImage; 192 | } 193 | 194 | // Helper methods for thumbnailForAsset:maxPixelSize: 195 | static size_t getAssetBytesCallback(void *info, void *buffer, off_t position, size_t count) { 196 | ALAssetRepresentation *rep = (__bridge id)info; 197 | 198 | NSError *error = nil; 199 | size_t countRead = [rep getBytes:(uint8_t *)buffer fromOffset:position length:count error:&error]; 200 | 201 | if (countRead == 0 && error) { 202 | // We have no way of passing this info back to the caller, so we log it, at least. 203 | NSLog(@"thumbnailForAsset:maxPixelSize: got an error reading an asset: %@", error); 204 | } 205 | 206 | return countRead; 207 | } 208 | 209 | static void releaseAssetCallback(void *info) { 210 | // The info here is an ALAssetRepresentation which we CFRetain in thumbnailForAsset:maxPixelSize:. 211 | // This release balances that retain. 212 | CFRelease(info); 213 | } 214 | 215 | // Returns a UIImage for the given asset, with size length at most the passed size. 216 | // The resulting UIImage will be already rotated to UIImageOrientationUp, so its CGImageRef 217 | // can be used directly without additional rotation handling. 218 | // This is done synchronously, so you should call this method on a background queue/thread. 219 | - (CGImageRef)thumbnailForAsset:(ALAsset *)asset maxPixelSize:(NSUInteger)size { 220 | NSParameterAssert(asset != nil); 221 | NSParameterAssert(size > 0); 222 | 223 | ALAssetRepresentation *rep = [asset defaultRepresentation]; 224 | 225 | CGDataProviderDirectCallbacks callbacks = { 226 | .version = 0, 227 | .getBytePointer = NULL, 228 | .releaseBytePointer = NULL, 229 | .getBytesAtPosition = getAssetBytesCallback, 230 | .releaseInfo = releaseAssetCallback, 231 | }; 232 | 233 | CGDataProviderRef provider = CGDataProviderCreateDirect((void *)CFBridgingRetain(rep), [rep size], &callbacks); 234 | CGImageSourceRef source = CGImageSourceCreateWithDataProvider(provider, NULL); 235 | 236 | CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(source, 0, (__bridge CFDictionaryRef) @{ 237 | (NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES, 238 | (NSString *)kCGImageSourceThumbnailMaxPixelSize : @(size), 239 | (NSString *)kCGImageSourceCreateThumbnailWithTransform : @YES, 240 | }); 241 | CFRelease(source); 242 | CFRelease(provider); 243 | 244 | if (!imageRef) { 245 | return nil; 246 | } 247 | 248 | return imageRef; 249 | } 250 | 251 | @end 252 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFImagePickerController.h: -------------------------------------------------------------------------------- 1 | // 2 | // JFImagePickerController.h 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "JFAssetHelper.h" 11 | #import "JFImageManager.h" 12 | 13 | @interface JFImagePickerController : UINavigationController 14 | 15 | - (JFImagePickerController *)initWithPreviewIndex:(NSInteger)index ; 16 | 17 | @property (nonatomic, weak) id pickerDelegate; 18 | /** 19 | 当退出编辑模式时需调用clear,用来清理内存,已选择照片的缓存 20 | **/ 21 | + (void)clear; 22 | + (void)setMaxCount:(NSInteger)maxCount; 23 | - (UIToolbar *)customToolbar; 24 | - (void)setLeftTitle:(NSString *)title; 25 | - (void)cancel; 26 | 27 | - (NSArray *)imagesWithType:(NSInteger)type; 28 | - (NSArray *)assets; 29 | 30 | @end 31 | 32 | @protocol JFImagePickerDelegate 33 | 34 | - (void)imagePickerDidFinished:(JFImagePickerController *)picker; 35 | - (void)imagePickerDidCancel:(JFImagePickerController *)picker; 36 | 37 | @end 38 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFImagePickerController.m: -------------------------------------------------------------------------------- 1 | // 2 | // JFImagePickerController.m 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import "JFImagePickerController.h" 10 | #import "JFImageGroupTableViewController.h" 11 | #import "JFPhotoBrowserViewController.h" 12 | #import "JFImageCollectionViewController.h" 13 | #import "JFAssetHelper.h" 14 | #import "JFImageManager.h" 15 | 16 | @interface JFImagePickerController () 17 | 18 | @end 19 | 20 | @implementation JFImagePickerController { 21 | UIBarButtonItem *selectNum; 22 | UIBarButtonItem *preview; 23 | UIToolbar *toolbar; 24 | JFImageCollectionViewController *collectionViewController; 25 | UIStatusBarStyle tempBarStyle; 26 | } 27 | 28 | - (JFImagePickerController *)initWithPreviewIndex:(NSInteger)index { 29 | self = [super initWithRootViewController:[JFImageGroupTableViewController new]]; 30 | if (self) { 31 | ASSETHELPER.previewIndex = index; 32 | } 33 | return self; 34 | } 35 | 36 | - (id)initWithRootViewController:(UIViewController *)rootViewController { 37 | self = [super initWithRootViewController:[JFImageGroupTableViewController new]]; 38 | if (self) { 39 | ASSETHELPER.previewIndex = -1; 40 | } 41 | return self; 42 | } 43 | 44 | - (void)viewWillAppear:(BOOL)animated{ 45 | [super viewWillAppear:animated]; 46 | if (ASSETHELPER.selectdPhotos.count>0) { 47 | preview.title = @"预览"; 48 | } else { 49 | preview.title = @""; 50 | } 51 | } 52 | 53 | - (void)viewDidAppear:(BOOL)animated{ 54 | [super viewDidAppear:animated]; 55 | } 56 | 57 | - (void)viewDidLoad 58 | { 59 | [super viewDidLoad]; 60 | dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 61 | tempBarStyle = [UIApplication sharedApplication].statusBarStyle; 62 | if (tempBarStyle!=UIStatusBarStyleLightContent) { 63 | [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES]; 64 | } 65 | }); 66 | 67 | toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height-44, [UIScreen mainScreen].bounds.size.width, 44)]; 68 | toolbar.tintColor = [UIColor whiteColor]; 69 | toolbar.barStyle = UIBarStyleBlack; 70 | [self.view addSubview:toolbar]; 71 | UIBarButtonItem *leftFix = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; 72 | UIBarButtonItem *rightFix = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; 73 | preview = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(preview)]; 74 | UIBarButtonItem *fix = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 75 | selectNum = [[UIBarButtonItem alloc] initWithTitle:@"0/9" style:UIBarButtonItemStylePlain target:nil action:nil]; 76 | UIBarButtonItem *fix2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 77 | UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(choiceDone)]; 78 | [toolbar setItems:@[leftFix, preview, fix, selectNum, fix2, done, rightFix]]; 79 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCount:) name:@"selectdPhotos" object:nil]; 80 | selectNum.title = [NSString stringWithFormat:@"%ld/%@", (unsigned long)ASSETHELPER.selectdPhotos.count,@(ASSETHELPER.maxCount)]; 81 | } 82 | 83 | - (void)setLeftTitle:(NSString *)title{ 84 | preview.title = title; 85 | } 86 | 87 | - (UIToolbar *)customToolbar{ 88 | return toolbar; 89 | } 90 | 91 | + (void)setMaxCount:(NSInteger)maxCount { 92 | ASSETHELPER.maxCount = maxCount; 93 | } 94 | 95 | - (void)changeCount:(NSNotification *)notifi{ 96 | selectNum.title = [NSString stringWithFormat:@"%ld/%@", (unsigned long)ASSETHELPER.selectdPhotos.count,@(ASSETHELPER.maxCount)]; 97 | if (![preview.title isEqualToString:@"取消"]) { 98 | if (ASSETHELPER.selectdPhotos.count>0) { 99 | preview.title = @"预览"; 100 | } else { 101 | preview.title = @""; 102 | } 103 | } 104 | } 105 | 106 | - (void)cancel{ 107 | if (_pickerDelegate) { 108 | if (tempBarStyle!=UIStatusBarStyleLightContent) { 109 | [[UIApplication sharedApplication] setStatusBarStyle:tempBarStyle animated:NO]; 110 | } 111 | [_pickerDelegate imagePickerDidCancel:self]; 112 | } 113 | } 114 | 115 | - (void)preview{ 116 | if (preview.title.length<=0) { 117 | return; 118 | } 119 | if ([preview.title isEqualToString:@"取消"]) { 120 | [self cancel]; 121 | return; 122 | } 123 | if ([preview.title isEqualToString:@"预览"]) { 124 | preview.title = @"取消"; 125 | ASSETHELPER.previewIndex = 0; 126 | collectionViewController = (JFImageCollectionViewController *)self.visibleViewController; 127 | JFPhotoBrowserViewController *photoBrowser = [[JFPhotoBrowserViewController alloc] initWithPreview]; 128 | photoBrowser.delegate = self; 129 | [self pushViewController:photoBrowser animated:YES]; 130 | } else { 131 | [self cancel]; 132 | } 133 | } 134 | 135 | - (void)choiceDone{ 136 | if (_pickerDelegate) { 137 | if (tempBarStyle!=UIStatusBarStyleLightContent) { 138 | [[UIApplication sharedApplication] setStatusBarStyle:tempBarStyle animated:NO]; 139 | } 140 | [_pickerDelegate imagePickerDidFinished:self]; 141 | } 142 | } 143 | 144 | - (void)didReceiveMemoryWarning 145 | { 146 | [super didReceiveMemoryWarning]; 147 | // Dispose of any resources that can be recreated. 148 | } 149 | 150 | - (NSInteger)numOfPhotosFromPhotoBrowser:(JFPhotoBrowserViewController *)browser{ 151 | return ASSETHELPER.selectdPhotos.count; 152 | } 153 | 154 | - (NSInteger)currentIndexFromPhotoBrowser:(JFPhotoBrowserViewController *)browser{ 155 | return ASSETHELPER.previewIndex; 156 | } 157 | 158 | - (ALAsset *)assetWithIndex:(NSInteger)index fromPhotoBrowser:(JFPhotoBrowserViewController *)browser{ 159 | return ASSETHELPER.selectdAssets[index]; 160 | } 161 | 162 | - (JFImagePickerViewCell *)cellForRow:(NSInteger)row{ 163 | return (JFImagePickerViewCell *)[[collectionViewController collectionView] cellForItemAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0]]; 164 | } 165 | 166 | - (NSArray *)imagesWithType:(NSInteger)type{ 167 | NSMutableArray *temp = [NSMutableArray array]; 168 | for (ALAsset *asset in ASSETHELPER.selectdAssets) { 169 | [temp addObject:[ASSETHELPER getImageFromAsset:asset type:type]]; 170 | } 171 | return temp; 172 | } 173 | 174 | - (NSArray *)assets{ 175 | return ASSETHELPER.selectdAssets; 176 | } 177 | 178 | + (void)clear{ 179 | [ASSETHELPER clearData]; 180 | [[JFImageManager sharedManager] clearMem]; 181 | } 182 | 183 | - (NSUInteger)supportedInterfaceOrientations{ 184 | return UIInterfaceOrientationMaskPortrait; 185 | } 186 | 187 | - (BOOL)shouldAutorotate{ 188 | return NO; 189 | } 190 | 191 | @end 192 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFImagePickerViewCell.h: -------------------------------------------------------------------------------- 1 | // 2 | // JFImagePickerViewCell.h 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface JFImagePickerViewCell : UICollectionViewCell 12 | 13 | @property (nonatomic, strong) NSIndexPath *indexPath; 14 | @property (nonatomic, strong) UIImageView *imageView; 15 | @property (nonatomic, strong) UILabel *numOfSelect; 16 | - (void)selectOfNum:(NSInteger)num; 17 | 18 | @end 19 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFImagePickerViewCell.m: -------------------------------------------------------------------------------- 1 | // 2 | // JFImagePickerViewCell.m 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import "JFImagePickerViewCell.h" 10 | #import "JFAssetHelper.h" 11 | 12 | @implementation JFImagePickerViewCell { 13 | UIView *placeholder; 14 | } 15 | 16 | - (id)initWithFrame:(CGRect)frame 17 | { 18 | self = [super initWithFrame:frame]; 19 | if (self) { 20 | _imageView = [[UIImageView alloc] initWithFrame:self.bounds]; 21 | _imageView.contentMode = UIViewContentModeScaleAspectFill; 22 | _imageView.clipsToBounds = YES; 23 | [self addSubview:_imageView]; 24 | placeholder = [[UIView alloc] initWithFrame:CGRectMake(self.frame.size.width-30, 4, 26, 26)]; 25 | placeholder.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.1]; 26 | placeholder.layer.cornerRadius = 13; 27 | placeholder.layer.borderColor = [UIColor whiteColor].CGColor; 28 | placeholder.layer.borderWidth = 1; 29 | placeholder.userInteractionEnabled = NO; 30 | [self addSubview:placeholder]; 31 | UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCell:)]; 32 | [self addGestureRecognizer:tap]; 33 | } 34 | return self; 35 | } 36 | 37 | - (void)selectOfNum:(NSInteger)num{ 38 | if (_numOfSelect==nil&&num!=-1) { 39 | placeholder.hidden = YES; 40 | _numOfSelect = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width-30, 4, 26, 26)]; 41 | _numOfSelect.backgroundColor = [APP_COLOR colorWithAlphaComponent:.9]; 42 | _numOfSelect.textAlignment = NSTextAlignmentCenter; 43 | _numOfSelect.textColor = [UIColor whiteColor]; 44 | _numOfSelect.font = [UIFont systemFontOfSize:15]; 45 | _numOfSelect.layer.cornerRadius = 13; 46 | _numOfSelect.layer.borderColor = [UIColor whiteColor].CGColor; 47 | _numOfSelect.layer.borderWidth = 1; 48 | _numOfSelect.clipsToBounds = YES; 49 | [self addSubview:_numOfSelect]; 50 | _numOfSelect.text = @(num).stringValue; 51 | _numOfSelect.transform = CGAffineTransformMakeScale(.5, .5); 52 | [UIView animateWithDuration:.3 delay:0 usingSpringWithDamping:.5 initialSpringVelocity:.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{ 53 | _numOfSelect.transform = CGAffineTransformIdentity; 54 | } completion:nil]; 55 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadNum:) name:@"reloadNum" object:nil]; 56 | } else { 57 | placeholder.hidden = NO; 58 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 59 | [_numOfSelect removeFromSuperview]; 60 | _numOfSelect = nil; 61 | } 62 | } 63 | 64 | - (void)removeFromSuperview{ 65 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 66 | [super removeFromSuperview]; 67 | } 68 | 69 | - (void)reloadNum:(NSNotification *)notifi{ 70 | for (NSDictionary *temp in ASSETHELPER.selectdPhotos) { 71 | if ([[[temp allKeys] firstObject] isEqualToString:[NSString stringWithFormat:@"%ld-%ld", (long)_indexPath.row, (long)ASSETHELPER.currentGroupIndex]]) { 72 | _numOfSelect.text = [[[temp allValues] firstObject] stringValue]; 73 | } 74 | } 75 | } 76 | 77 | - (void)tapCell:(UITapGestureRecognizer *)tap{ 78 | CGPoint location = [tap locationInView:self]; 79 | if (CGRectContainsPoint(CGRectMake(placeholder.frame.origin.x-5, placeholder.frame.origin.y-5, placeholder.frame.size.width+10, placeholder.frame.size.height+10), location)) { 80 | if (self.numOfSelect==nil&&ASSETHELPER.selectdPhotos.count>= ASSETHELPER.maxCount) { 81 | [[[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"最多可以选择%@张照片",@(ASSETHELPER.maxCount)] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show]; 82 | return; 83 | } 84 | if (self.numOfSelect==nil) { 85 | [ASSETHELPER.selectdPhotos addObject:@{[NSString stringWithFormat:@"%ld-%ld",(long)_indexPath.row, (long)ASSETHELPER.currentGroupIndex]: @(ASSETHELPER.selectdPhotos.count+1)}]; 86 | 87 | [ASSETHELPER.selectdAssets addObject:[ASSETHELPER getAssetAtIndex:_indexPath.row]]; 88 | 89 | [self selectOfNum:ASSETHELPER.selectdPhotos.count]; 90 | } else { 91 | NSInteger index = 0; 92 | NSInteger num = 0; 93 | for (NSDictionary *dict in ASSETHELPER.selectdPhotos) { 94 | if ([[[dict allKeys] firstObject] isEqualToString:[NSString stringWithFormat:@"%ld-%ld",(long)_indexPath.row, (long)ASSETHELPER.currentGroupIndex]]) { 95 | index = [ASSETHELPER.selectdPhotos indexOfObject:dict]; 96 | num = [[[dict allValues] firstObject] intValue]; 97 | } 98 | } 99 | for (NSDictionary *dict in [ASSETHELPER.selectdPhotos copy]) { 100 | if ([[[dict allValues] firstObject] intValue]>num) { 101 | NSInteger index = [ASSETHELPER.selectdPhotos indexOfObject:dict]; 102 | [ASSETHELPER.selectdPhotos removeObject:dict]; 103 | [ASSETHELPER.selectdPhotos insertObject:@{[[dict allKeys] firstObject]: @([[[dict allValues] firstObject] intValue]-1)} atIndex:index]; 104 | } 105 | } 106 | 107 | 108 | [ASSETHELPER.selectdAssets removeObjectAtIndex:index]; 109 | [ASSETHELPER.selectdPhotos removeObjectAtIndex:index]; 110 | [self selectOfNum:-1]; 111 | [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadNum" object:nil]; 112 | } 113 | [[NSNotificationCenter defaultCenter] postNotificationName:@"selectdPhotos" object:nil]; 114 | } else { 115 | [[NSNotificationCenter defaultCenter] postNotificationName:@"showNormalPhotoBrowser" object:_indexPath]; 116 | } 117 | } 118 | 119 | @end 120 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFPhotoBrowserViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // JFPhotoBrowserViewController.h 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | #import "JFImagePickerViewCell.h" 12 | @interface JFPhotoBrowserViewController : UIViewController 13 | @property (nonatomic, assign) NSInteger maxCount; 14 | - (JFPhotoBrowserViewController *)initWithPreview; 15 | - (JFPhotoBrowserViewController *)initWithNormal; 16 | @property (nonatomic, weak) id delegate; 17 | 18 | @end 19 | 20 | @protocol JDPhotoBrowserDelegate 21 | 22 | - (ALAsset *)assetWithIndex:(NSInteger)index fromPhotoBrowser:(JFPhotoBrowserViewController *)browser; 23 | - (NSInteger)numOfPhotosFromPhotoBrowser:(JFPhotoBrowserViewController *)browser; 24 | - (NSInteger)currentIndexFromPhotoBrowser:(JFPhotoBrowserViewController *)browser; 25 | @optional 26 | - (void)photoBrowser:(JFPhotoBrowserViewController *)browser didShowPage:(NSInteger)page; 27 | - (JFImagePickerViewCell *)cellForRow:(NSInteger)row; 28 | 29 | @end 30 | -------------------------------------------------------------------------------- /3DSource/JFImagePickerController/JFPhotoView.h: -------------------------------------------------------------------------------- 1 | // 2 | // JFPhotoView.h 3 | // JFImagePickerController 4 | // 5 | // Created by Johnil on 15-7-3. 6 | // Copyright (c) 2015年 Johnil. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | @interface JFPhotoView : UIScrollView 13 | 14 | @property (nonatomic, strong) UIImageView *imageView; 15 | @property (nonatomic, weak) id photoDelegate; 16 | 17 | - (void)reloadRotate; 18 | - (void)reset; 19 | - (void)clearMemory; 20 | - (void)loadImage:(ALAsset *)asset; 21 | 22 | @end 23 | 24 | @protocol JFPhotoDelegate 25 | 26 | - (void)tap; 27 | 28 | @end -------------------------------------------------------------------------------- /3DSource/SDWebImage/NSData+ImageContentType.h: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Fabrice Aneche on 06/01/14. 3 | // Copyright (c) 2014 Dailymotion. All rights reserved. 4 | // 5 | 6 | #import 7 | 8 | @interface NSData (ImageContentType) 9 | 10 | /** 11 | * Compute the content type for an image data 12 | * 13 | * @param data the input data 14 | * 15 | * @return the content type as string (i.e. image/jpeg, image/gif) 16 | */ 17 | + (NSString *)sd_contentTypeForImageData:(NSData *)data; 18 | 19 | @end 20 | 21 | 22 | @interface NSData (ImageContentTypeDeprecated) 23 | 24 | + (NSString *)contentTypeForImageData:(NSData *)data __deprecated_msg("Use `sd_contentTypeForImageData:`"); 25 | 26 | @end 27 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/NSData+ImageContentType.m: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Fabrice Aneche on 06/01/14. 3 | // Copyright (c) 2014 Dailymotion. All rights reserved. 4 | // 5 | 6 | #import "NSData+ImageContentType.h" 7 | 8 | 9 | @implementation NSData (ImageContentType) 10 | 11 | + (NSString *)sd_contentTypeForImageData:(NSData *)data { 12 | uint8_t c; 13 | [data getBytes:&c length:1]; 14 | switch (c) { 15 | case 0xFF: 16 | return @"image/jpeg"; 17 | case 0x89: 18 | return @"image/png"; 19 | case 0x47: 20 | return @"image/gif"; 21 | case 0x49: 22 | case 0x4D: 23 | return @"image/tiff"; 24 | case 0x52: 25 | // R as RIFF for WEBP 26 | if ([data length] < 12) { 27 | return nil; 28 | } 29 | 30 | NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; 31 | if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { 32 | return @"image/webp"; 33 | } 34 | 35 | return nil; 36 | } 37 | return nil; 38 | } 39 | 40 | @end 41 | 42 | 43 | @implementation NSData (ImageContentTypeDeprecated) 44 | 45 | + (NSString *)contentTypeForImageData:(NSData *)data { 46 | return [self sd_contentTypeForImageData:data]; 47 | } 48 | 49 | @end 50 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/SDImageCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | 12 | typedef NS_ENUM(NSInteger, SDImageCacheType) { 13 | /** 14 | * The image wasn't available the SDWebImage caches, but was downloaded from the web. 15 | */ 16 | SDImageCacheTypeNone, 17 | /** 18 | * The image was obtained from the disk cache. 19 | */ 20 | SDImageCacheTypeDisk, 21 | /** 22 | * The image was obtained from the memory cache. 23 | */ 24 | SDImageCacheTypeMemory 25 | }; 26 | 27 | typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType); 28 | 29 | typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache); 30 | 31 | typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); 32 | 33 | /** 34 | * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed 35 | * asynchronous so it doesn’t add unnecessary latency to the UI. 36 | */ 37 | @interface SDImageCache : NSObject 38 | 39 | /** 40 | * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory. 41 | * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. 42 | */ 43 | @property (assign, nonatomic) BOOL shouldDecompressImages; 44 | 45 | /** 46 | * disable iCloud backup [defaults to YES] 47 | */ 48 | @property (assign, nonatomic) BOOL shouldDisableiCloud; 49 | 50 | /** 51 | * use memory cache [defaults to YES] 52 | */ 53 | @property (assign, nonatomic) BOOL shouldCacheImagesInMemory; 54 | 55 | /** 56 | * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. 57 | */ 58 | @property (assign, nonatomic) NSUInteger maxMemoryCost; 59 | 60 | /** 61 | * The maximum number of objects the cache should hold. 62 | */ 63 | @property (assign, nonatomic) NSUInteger maxMemoryCountLimit; 64 | 65 | /** 66 | * The maximum length of time to keep an image in the cache, in seconds 67 | */ 68 | @property (assign, nonatomic) NSInteger maxCacheAge; 69 | 70 | /** 71 | * The maximum size of the cache, in bytes. 72 | */ 73 | @property (assign, nonatomic) NSUInteger maxCacheSize; 74 | 75 | /** 76 | * Returns global shared cache instance 77 | * 78 | * @return SDImageCache global instance 79 | */ 80 | + (SDImageCache *)sharedImageCache; 81 | 82 | /** 83 | * Init a new cache store with a specific namespace 84 | * 85 | * @param ns The namespace to use for this cache store 86 | */ 87 | - (id)initWithNamespace:(NSString *)ns; 88 | 89 | /** 90 | * Init a new cache store with a specific namespace and directory 91 | * 92 | * @param ns The namespace to use for this cache store 93 | * @param directory Directory to cache disk images in 94 | */ 95 | - (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory; 96 | 97 | -(NSString *)makeDiskCachePath:(NSString*)fullNamespace; 98 | 99 | /** 100 | * Add a read-only cache path to search for images pre-cached by SDImageCache 101 | * Useful if you want to bundle pre-loaded images with your app 102 | * 103 | * @param path The path to use for this read-only cache path 104 | */ 105 | - (void)addReadOnlyCachePath:(NSString *)path; 106 | 107 | /** 108 | * Store an image into memory and disk cache at the given key. 109 | * 110 | * @param image The image to store 111 | * @param key The unique image cache key, usually it's image absolute URL 112 | */ 113 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key; 114 | 115 | /** 116 | * Store an image into memory and optionally disk cache at the given key. 117 | * 118 | * @param image The image to store 119 | * @param key The unique image cache key, usually it's image absolute URL 120 | * @param toDisk Store the image to disk cache if YES 121 | */ 122 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; 123 | 124 | /** 125 | * Store an image into memory and optionally disk cache at the given key. 126 | * 127 | * @param image The image to store 128 | * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage 129 | * @param imageData The image data as returned by the server, this representation will be used for disk storage 130 | * instead of converting the given image object into a storable/compressed image format in order 131 | * to save quality and CPU 132 | * @param key The unique image cache key, usually it's image absolute URL 133 | * @param toDisk Store the image to disk cache if YES 134 | */ 135 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; 136 | 137 | /** 138 | * Store image NSData into disk cache at the given key. 139 | * 140 | * @param imageData The image data to store 141 | * @param key The unique image cache key, usually it's image absolute URL 142 | */ 143 | - (void)storeImageDataToDisk:(NSData *)imageData forKey:(NSString *)key; 144 | 145 | /** 146 | * Query the disk cache asynchronously. 147 | * 148 | * @param key The unique key used to store the wanted image 149 | */ 150 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; 151 | 152 | /** 153 | * Query the memory cache synchronously. 154 | * 155 | * @param key The unique key used to store the wanted image 156 | */ 157 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; 158 | 159 | /** 160 | * Query the disk cache synchronously after checking the memory cache. 161 | * 162 | * @param key The unique key used to store the wanted image 163 | */ 164 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key; 165 | 166 | /** 167 | * Remove the image from memory and disk cache asynchronously 168 | * 169 | * @param key The unique image cache key 170 | */ 171 | - (void)removeImageForKey:(NSString *)key; 172 | 173 | 174 | /** 175 | * Remove the image from memory and disk cache asynchronously 176 | * 177 | * @param key The unique image cache key 178 | * @param completion An block that should be executed after the image has been removed (optional) 179 | */ 180 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion; 181 | 182 | /** 183 | * Remove the image from memory and optionally disk cache asynchronously 184 | * 185 | * @param key The unique image cache key 186 | * @param fromDisk Also remove cache entry from disk if YES 187 | */ 188 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; 189 | 190 | /** 191 | * Remove the image from memory and optionally disk cache asynchronously 192 | * 193 | * @param key The unique image cache key 194 | * @param fromDisk Also remove cache entry from disk if YES 195 | * @param completion An block that should be executed after the image has been removed (optional) 196 | */ 197 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion; 198 | 199 | /** 200 | * Clear all memory cached images 201 | */ 202 | - (void)clearMemory; 203 | 204 | /** 205 | * Clear all disk cached images. Non-blocking method - returns immediately. 206 | * @param completion An block that should be executed after cache expiration completes (optional) 207 | */ 208 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion; 209 | 210 | /** 211 | * Clear all disk cached images 212 | * @see clearDiskOnCompletion: 213 | */ 214 | - (void)clearDisk; 215 | 216 | /** 217 | * Remove all expired cached image from disk. Non-blocking method - returns immediately. 218 | * @param completionBlock An block that should be executed after cache expiration completes (optional) 219 | */ 220 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock; 221 | 222 | /** 223 | * Remove all expired cached image from disk 224 | * @see cleanDiskWithCompletionBlock: 225 | */ 226 | - (void)cleanDisk; 227 | 228 | /** 229 | * Get the size used by the disk cache 230 | */ 231 | - (NSUInteger)getSize; 232 | 233 | /** 234 | * Get the number of images in the disk cache 235 | */ 236 | - (NSUInteger)getDiskCount; 237 | 238 | /** 239 | * Asynchronously calculate the disk cache's size. 240 | */ 241 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock; 242 | 243 | /** 244 | * Async check if image exists in disk cache already (does not load the image) 245 | * 246 | * @param key the key describing the url 247 | * @param completionBlock the block to be executed when the check is done. 248 | * @note the completion block will be always executed on the main queue 249 | */ 250 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 251 | 252 | /** 253 | * Check if image exists in disk cache already (does not load the image) 254 | * 255 | * @param key the key describing the url 256 | * 257 | * @return YES if an image exists for the given key 258 | */ 259 | - (BOOL)diskImageExistsWithKey:(NSString *)key; 260 | 261 | /** 262 | * Get the cache path for a certain key (needs the cache path root folder) 263 | * 264 | * @param key the key (can be obtained from url using cacheKeyForURL) 265 | * @param path the cache path root folder 266 | * 267 | * @return the cache path 268 | */ 269 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path; 270 | 271 | /** 272 | * Get the default cache path for a certain key 273 | * 274 | * @param key the key (can be obtained from url using cacheKeyForURL) 275 | * 276 | * @return the default cache path 277 | */ 278 | - (NSString *)defaultCachePathForKey:(NSString *)key; 279 | 280 | @end 281 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/SDWebImageCompat.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * (c) Jamie Pinkham 5 | * 6 | * For the full copyright and license information, please view the LICENSE 7 | * file that was distributed with this source code. 8 | */ 9 | 10 | #import 11 | 12 | #ifdef __OBJC_GC__ 13 | #error SDWebImage does not support Objective-C Garbage Collection 14 | #endif 15 | 16 | #if __IPHONE_OS_VERSION_MIN_REQUIRED != 20000 && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 17 | #error SDWebImage doesn't support Deployment Target version < 5.0 18 | #endif 19 | 20 | #if !TARGET_OS_IPHONE 21 | #import 22 | #ifndef UIImage 23 | #define UIImage NSImage 24 | #endif 25 | #ifndef UIImageView 26 | #define UIImageView NSImageView 27 | #endif 28 | #else 29 | 30 | #import 31 | 32 | #endif 33 | 34 | #ifndef NS_ENUM 35 | #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type 36 | #endif 37 | 38 | #ifndef NS_OPTIONS 39 | #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type 40 | #endif 41 | 42 | #if OS_OBJECT_USE_OBJC 43 | #undef SDDispatchQueueRelease 44 | #undef SDDispatchQueueSetterSementics 45 | #define SDDispatchQueueRelease(q) 46 | #define SDDispatchQueueSetterSementics strong 47 | #else 48 | #undef SDDispatchQueueRelease 49 | #undef SDDispatchQueueSetterSementics 50 | #define SDDispatchQueueRelease(q) (dispatch_release(q)) 51 | #define SDDispatchQueueSetterSementics assign 52 | #endif 53 | 54 | extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); 55 | 56 | typedef void(^SDWebImageNoParamsBlock)(); 57 | 58 | extern NSString *const SDWebImageErrorDomain; 59 | 60 | #define dispatch_main_sync_safe(block)\ 61 | if ([NSThread isMainThread]) {\ 62 | block();\ 63 | } else {\ 64 | dispatch_sync(dispatch_get_main_queue(), block);\ 65 | } 66 | 67 | #define dispatch_main_async_safe(block)\ 68 | if ([NSThread isMainThread]) {\ 69 | block();\ 70 | } else {\ 71 | dispatch_async(dispatch_get_main_queue(), block);\ 72 | } 73 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/SDWebImageCompat.m: -------------------------------------------------------------------------------- 1 | // 2 | // SDWebImageCompat.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 11/12/12. 6 | // Copyright (c) 2012 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "SDWebImageCompat.h" 10 | 11 | #if !__has_feature(objc_arc) 12 | #error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag 13 | #endif 14 | 15 | inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) { 16 | if (!image) { 17 | return nil; 18 | } 19 | 20 | if ([image.images count] > 0) { 21 | NSMutableArray *scaledImages = [NSMutableArray array]; 22 | 23 | for (UIImage *tempImage in image.images) { 24 | [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; 25 | } 26 | 27 | return [UIImage animatedImageWithImages:scaledImages duration:image.duration]; 28 | } 29 | else { 30 | if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { 31 | CGFloat scale = 1; 32 | if (key.length >= 8) { 33 | NSRange range = [key rangeOfString:@"@2x."]; 34 | if (range.location != NSNotFound) { 35 | scale = 2.0; 36 | } 37 | 38 | range = [key rangeOfString:@"@3x."]; 39 | if (range.location != NSNotFound) { 40 | scale = 3.0; 41 | } 42 | } 43 | 44 | UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; 45 | image = scaledImage; 46 | } 47 | return image; 48 | } 49 | } 50 | 51 | NSString *const SDWebImageErrorDomain = @"SDWebImageErrorDomain"; 52 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/SDWebImageDecoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * Created by james on 9/28/11. 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | #import 12 | #import "SDWebImageCompat.h" 13 | 14 | @interface UIImage (ForceDecode) 15 | 16 | + (UIImage *)decodedImageWithImage:(UIImage *)image; 17 | 18 | @end 19 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/SDWebImageDecoder.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * Created by james on 9/28/11. 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | #import "SDWebImageDecoder.h" 12 | 13 | @implementation UIImage (ForceDecode) 14 | 15 | + (UIImage *)decodedImageWithImage:(UIImage *)image { 16 | // while downloading huge amount of images 17 | // autorelease the bitmap context 18 | // and all vars to help system to free memory 19 | // when there are memory warning. 20 | // on iOS7, do not forget to call 21 | // [[SDImageCache sharedImageCache] clearMemory]; 22 | 23 | if (image == nil) { // Prevent "CGBitmapContextCreateImage: invalid context 0x0" error 24 | return nil; 25 | } 26 | 27 | @autoreleasepool{ 28 | // do not decode animated images 29 | if (image.images != nil) { 30 | return image; 31 | } 32 | 33 | CGImageRef imageRef = image.CGImage; 34 | 35 | CGImageAlphaInfo alpha = CGImageGetAlphaInfo(imageRef); 36 | BOOL anyAlpha = (alpha == kCGImageAlphaFirst || 37 | alpha == kCGImageAlphaLast || 38 | alpha == kCGImageAlphaPremultipliedFirst || 39 | alpha == kCGImageAlphaPremultipliedLast); 40 | if (anyAlpha) { 41 | return image; 42 | } 43 | 44 | // current 45 | CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(CGImageGetColorSpace(imageRef)); 46 | CGColorSpaceRef colorspaceRef = CGImageGetColorSpace(imageRef); 47 | 48 | BOOL unsupportedColorSpace = (imageColorSpaceModel == kCGColorSpaceModelUnknown || 49 | imageColorSpaceModel == kCGColorSpaceModelMonochrome || 50 | imageColorSpaceModel == kCGColorSpaceModelCMYK || 51 | imageColorSpaceModel == kCGColorSpaceModelIndexed); 52 | if (unsupportedColorSpace) { 53 | colorspaceRef = CGColorSpaceCreateDeviceRGB(); 54 | } 55 | 56 | size_t width = CGImageGetWidth(imageRef); 57 | size_t height = CGImageGetHeight(imageRef); 58 | NSUInteger bytesPerPixel = 4; 59 | NSUInteger bytesPerRow = bytesPerPixel * width; 60 | NSUInteger bitsPerComponent = 8; 61 | 62 | 63 | // kCGImageAlphaNone is not supported in CGBitmapContextCreate. 64 | // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast 65 | // to create bitmap graphics contexts without alpha info. 66 | CGContextRef context = CGBitmapContextCreate(NULL, 67 | width, 68 | height, 69 | bitsPerComponent, 70 | bytesPerRow, 71 | colorspaceRef, 72 | kCGBitmapByteOrderDefault|kCGImageAlphaNoneSkipLast); 73 | 74 | // Draw the image into the context and retrieve the new bitmap image without alpha 75 | CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); 76 | CGImageRef imageRefWithoutAlpha = CGBitmapContextCreateImage(context); 77 | UIImage *imageWithoutAlpha = [UIImage imageWithCGImage:imageRefWithoutAlpha 78 | scale:image.scale 79 | orientation:image.imageOrientation]; 80 | 81 | if (unsupportedColorSpace) { 82 | CGColorSpaceRelease(colorspaceRef); 83 | } 84 | 85 | CGContextRelease(context); 86 | CGImageRelease(imageRefWithoutAlpha); 87 | 88 | return imageWithoutAlpha; 89 | } 90 | } 91 | 92 | @end 93 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/SDWebImageDownloader.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | #import "SDWebImageOperation.h" 12 | 13 | typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { 14 | SDWebImageDownloaderLowPriority = 1 << 0, 15 | SDWebImageDownloaderProgressiveDownload = 1 << 1, 16 | 17 | /** 18 | * By default, request prevent the use of NSURLCache. With this flag, NSURLCache 19 | * is used with default policies. 20 | */ 21 | SDWebImageDownloaderUseNSURLCache = 1 << 2, 22 | 23 | /** 24 | * Call completion block with nil image/imageData if the image was read from NSURLCache 25 | * (to be combined with `SDWebImageDownloaderUseNSURLCache`). 26 | */ 27 | 28 | SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, 29 | /** 30 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 31 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 32 | */ 33 | 34 | SDWebImageDownloaderContinueInBackground = 1 << 4, 35 | 36 | /** 37 | * Handles cookies stored in NSHTTPCookieStore by setting 38 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 39 | */ 40 | SDWebImageDownloaderHandleCookies = 1 << 5, 41 | 42 | /** 43 | * Enable to allow untrusted SSL certificates. 44 | * Useful for testing purposes. Use with caution in production. 45 | */ 46 | SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, 47 | 48 | /** 49 | * Put the image in the high priority queue. 50 | */ 51 | SDWebImageDownloaderHighPriority = 1 << 7, 52 | }; 53 | 54 | typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { 55 | /** 56 | * Default value. All download operations will execute in queue style (first-in-first-out). 57 | */ 58 | SDWebImageDownloaderFIFOExecutionOrder, 59 | 60 | /** 61 | * All download operations will execute in stack style (last-in-first-out). 62 | */ 63 | SDWebImageDownloaderLIFOExecutionOrder 64 | }; 65 | 66 | extern NSString *const SDWebImageDownloadStartNotification; 67 | extern NSString *const SDWebImageDownloadStopNotification; 68 | 69 | typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); 70 | 71 | typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); 72 | 73 | typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers); 74 | 75 | /** 76 | * Asynchronous downloader dedicated and optimized for image loading. 77 | */ 78 | @interface SDWebImageDownloader : NSObject 79 | 80 | /** 81 | * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory. 82 | * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. 83 | */ 84 | @property (assign, nonatomic) BOOL shouldDecompressImages; 85 | 86 | @property (assign, nonatomic) NSInteger maxConcurrentDownloads; 87 | 88 | /** 89 | * Shows the current amount of downloads that still need to be downloaded 90 | */ 91 | @property (readonly, nonatomic) NSUInteger currentDownloadCount; 92 | 93 | 94 | /** 95 | * The timeout value (in seconds) for the download operation. Default: 15.0. 96 | */ 97 | @property (assign, nonatomic) NSTimeInterval downloadTimeout; 98 | 99 | 100 | /** 101 | * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. 102 | */ 103 | @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; 104 | 105 | /** 106 | * Singleton method, returns the shared instance 107 | * 108 | * @return global shared instance of downloader class 109 | */ 110 | + (SDWebImageDownloader *)sharedDownloader; 111 | 112 | /** 113 | * Set the default URL credential to be set for request operations. 114 | */ 115 | @property (strong, nonatomic) NSURLCredential *urlCredential; 116 | 117 | /** 118 | * Set username 119 | */ 120 | @property (strong, nonatomic) NSString *username; 121 | 122 | /** 123 | * Set password 124 | */ 125 | @property (strong, nonatomic) NSString *password; 126 | 127 | /** 128 | * Set filter to pick headers for downloading image HTTP request. 129 | * 130 | * This block will be invoked for each downloading image request, returned 131 | * NSDictionary will be used as headers in corresponding HTTP request. 132 | */ 133 | @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter; 134 | 135 | /** 136 | * Set a value for a HTTP header to be appended to each download HTTP request. 137 | * 138 | * @param value The value for the header field. Use `nil` value to remove the header. 139 | * @param field The name of the header field to set. 140 | */ 141 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; 142 | 143 | /** 144 | * Returns the value of the specified HTTP header field. 145 | * 146 | * @return The value associated with the header field field, or `nil` if there is no corresponding header field. 147 | */ 148 | - (NSString *)valueForHTTPHeaderField:(NSString *)field; 149 | 150 | /** 151 | * Sets a subclass of `SDWebImageDownloaderOperation` as the default 152 | * `NSOperation` to be used each time SDWebImage constructs a request 153 | * operation to download an image. 154 | * 155 | * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set 156 | * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. 157 | */ 158 | - (void)setOperationClass:(Class)operationClass; 159 | 160 | /** 161 | * Creates a SDWebImageDownloader async downloader instance with a given URL 162 | * 163 | * The delegate will be informed when the image is finish downloaded or an error has happen. 164 | * 165 | * @see SDWebImageDownloaderDelegate 166 | * 167 | * @param url The URL to the image to download 168 | * @param options The options to be used for this download 169 | * @param progressBlock A block called repeatedly while the image is downloading 170 | * @param completedBlock A block called once the download is completed. 171 | * If the download succeeded, the image parameter is set, in case of error, 172 | * error parameter is set with the error. The last parameter is always YES 173 | * if SDWebImageDownloaderProgressiveDownload isn't use. With the 174 | * SDWebImageDownloaderProgressiveDownload option, this block is called 175 | * repeatedly with the partial image object and the finished argument set to NO 176 | * before to be called a last time with the full image and finished argument 177 | * set to YES. In case of error, the finished argument is always YES. 178 | * 179 | * @return A cancellable SDWebImageOperation 180 | */ 181 | - (id )downloadImageWithURL:(NSURL *)url 182 | options:(SDWebImageDownloaderOptions)options 183 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 184 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock; 185 | 186 | /** 187 | * Sets the download queue suspension state 188 | */ 189 | - (void)setSuspended:(BOOL)suspended; 190 | 191 | /** 192 | * Cancels all download operations in the queue 193 | */ 194 | - (void)cancelAllDownloads; 195 | 196 | @end 197 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/SDWebImageDownloaderOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageDownloader.h" 11 | #import "SDWebImageOperation.h" 12 | 13 | extern NSString *const SDWebImageDownloadStartNotification; 14 | extern NSString *const SDWebImageDownloadReceiveResponseNotification; 15 | extern NSString *const SDWebImageDownloadStopNotification; 16 | extern NSString *const SDWebImageDownloadFinishNotification; 17 | 18 | @interface SDWebImageDownloaderOperation : NSOperation 19 | 20 | /** 21 | * The request used by the operation's task. 22 | */ 23 | @property (strong, nonatomic, readonly) NSURLRequest *request; 24 | 25 | /** 26 | * The operation's task 27 | */ 28 | @property (strong, nonatomic, readonly) NSURLSessionTask *dataTask; 29 | 30 | 31 | @property (assign, nonatomic) BOOL shouldDecompressImages; 32 | 33 | /** 34 | * Was used to determine whether the URL connection should consult the credential storage for authenticating the connection. 35 | * @deprecated Not used for a couple of versions 36 | */ 37 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage __deprecated_msg("Property deprecated. Does nothing. Kept only for backwards compatibility"); 38 | 39 | /** 40 | * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. 41 | * 42 | * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. 43 | */ 44 | @property (nonatomic, strong) NSURLCredential *credential; 45 | 46 | /** 47 | * The SDWebImageDownloaderOptions for the receiver. 48 | */ 49 | @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; 50 | 51 | /** 52 | * The expected size of data. 53 | */ 54 | @property (assign, nonatomic) NSInteger expectedSize; 55 | 56 | /** 57 | * The response returned by the operation's connection. 58 | */ 59 | @property (strong, nonatomic) NSURLResponse *response; 60 | 61 | /** 62 | * Initializes a `SDWebImageDownloaderOperation` object 63 | * 64 | * @see SDWebImageDownloaderOperation 65 | * 66 | * @param request the URL request 67 | * @param session the URL session in which this operation will run 68 | * @param options downloader options 69 | * @param progressBlock the block executed when a new chunk of data arrives. 70 | * @note the progress block is executed on a background queue 71 | * @param completedBlock the block executed when the download is done. 72 | * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue 73 | * @param cancelBlock the block executed if the download (operation) is cancelled 74 | * 75 | * @return the initialized instance 76 | */ 77 | - (id)initWithRequest:(NSURLRequest *)request 78 | inSession:(NSURLSession *)session 79 | options:(SDWebImageDownloaderOptions)options 80 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 81 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock 82 | cancelled:(SDWebImageNoParamsBlock)cancelBlock; 83 | 84 | /** 85 | * Initializes a `SDWebImageDownloaderOperation` object 86 | * 87 | * @see SDWebImageDownloaderOperation 88 | * 89 | * @param request the URL request 90 | * @param options downloader options 91 | * @param progressBlock the block executed when a new chunk of data arrives. 92 | * @note the progress block is executed on a background queue 93 | * @param completedBlock the block executed when the download is done. 94 | * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue 95 | * @param cancelBlock the block executed if the download (operation) is cancelled 96 | * 97 | * @return the initialized instance. The operation will run in a separate session created for this operation 98 | */ 99 | - (id)initWithRequest:(NSURLRequest *)request 100 | options:(SDWebImageDownloaderOptions)options 101 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 102 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock 103 | cancelled:(SDWebImageNoParamsBlock)cancelBlock 104 | __deprecated_msg("Method deprecated. Use `initWithRequest:inSession:options:progress:completed:cancelled`"); 105 | 106 | @end 107 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/SDWebImageManager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | #import "SDWebImageOperation.h" 11 | #import "SDWebImageDownloader.h" 12 | #import "SDImageCache.h" 13 | 14 | typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { 15 | /** 16 | * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. 17 | * This flag disable this blacklisting. 18 | */ 19 | SDWebImageRetryFailed = 1 << 0, 20 | 21 | /** 22 | * By default, image downloads are started during UI interactions, this flags disable this feature, 23 | * leading to delayed download on UIScrollView deceleration for instance. 24 | */ 25 | SDWebImageLowPriority = 1 << 1, 26 | 27 | /** 28 | * This flag disables on-disk caching 29 | */ 30 | SDWebImageCacheMemoryOnly = 1 << 2, 31 | 32 | /** 33 | * This flag enables progressive download, the image is displayed progressively during download as a browser would do. 34 | * By default, the image is only displayed once completely downloaded. 35 | */ 36 | SDWebImageProgressiveDownload = 1 << 3, 37 | 38 | /** 39 | * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. 40 | * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. 41 | * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. 42 | * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. 43 | * 44 | * Use this flag only if you can't make your URLs static with embedded cache busting parameter. 45 | */ 46 | SDWebImageRefreshCached = 1 << 4, 47 | 48 | /** 49 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 50 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 51 | */ 52 | SDWebImageContinueInBackground = 1 << 5, 53 | 54 | /** 55 | * Handles cookies stored in NSHTTPCookieStore by setting 56 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 57 | */ 58 | SDWebImageHandleCookies = 1 << 6, 59 | 60 | /** 61 | * Enable to allow untrusted SSL certificates. 62 | * Useful for testing purposes. Use with caution in production. 63 | */ 64 | SDWebImageAllowInvalidSSLCertificates = 1 << 7, 65 | 66 | /** 67 | * By default, images are loaded in the order in which they were queued. This flag moves them to 68 | * the front of the queue. 69 | */ 70 | SDWebImageHighPriority = 1 << 8, 71 | 72 | /** 73 | * By default, placeholder images are loaded while the image is loading. This flag will delay the loading 74 | * of the placeholder image until after the image has finished loading. 75 | */ 76 | SDWebImageDelayPlaceholder = 1 << 9, 77 | 78 | /** 79 | * We usually don't call transformDownloadedImage delegate method on animated images, 80 | * as most transformation code would mangle it. 81 | * Use this flag to transform them anyway. 82 | */ 83 | SDWebImageTransformAnimatedImage = 1 << 10, 84 | 85 | /** 86 | * By default, image is added to the imageView after download. But in some cases, we want to 87 | * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) 88 | * Use this flag if you want to manually set the image in the completion when success 89 | */ 90 | SDWebImageAvoidAutoSetImage = 1 << 11 91 | }; 92 | 93 | typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL); 94 | 95 | typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL); 96 | 97 | typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url); 98 | 99 | 100 | @class SDWebImageManager; 101 | 102 | @protocol SDWebImageManagerDelegate 103 | 104 | @optional 105 | 106 | /** 107 | * Controls which image should be downloaded when the image is not found in the cache. 108 | * 109 | * @param imageManager The current `SDWebImageManager` 110 | * @param imageURL The url of the image to be downloaded 111 | * 112 | * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. 113 | */ 114 | - (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; 115 | 116 | /** 117 | * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. 118 | * NOTE: This method is called from a global queue in order to not to block the main thread. 119 | * 120 | * @param imageManager The current `SDWebImageManager` 121 | * @param image The image to transform 122 | * @param imageURL The url of the image to transform 123 | * 124 | * @return The transformed image object. 125 | */ 126 | - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; 127 | 128 | @end 129 | 130 | /** 131 | * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. 132 | * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). 133 | * You can use this class directly to benefit from web image downloading with caching in another context than 134 | * a UIView. 135 | * 136 | * Here is a simple example of how to use SDWebImageManager: 137 | * 138 | * @code 139 | 140 | SDWebImageManager *manager = [SDWebImageManager sharedManager]; 141 | [manager downloadImageWithURL:imageURL 142 | options:0 143 | progress:nil 144 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 145 | if (image) { 146 | // do something with image 147 | } 148 | }]; 149 | 150 | * @endcode 151 | */ 152 | @interface SDWebImageManager : NSObject 153 | 154 | @property (weak, nonatomic) id delegate; 155 | 156 | @property (strong, nonatomic, readonly) SDImageCache *imageCache; 157 | @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; 158 | 159 | /** 160 | * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can 161 | * be used to remove dynamic part of an image URL. 162 | * 163 | * The following example sets a filter in the application delegate that will remove any query-string from the 164 | * URL before to use it as a cache key: 165 | * 166 | * @code 167 | 168 | [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { 169 | url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; 170 | return [url absoluteString]; 171 | }]; 172 | 173 | * @endcode 174 | */ 175 | @property (nonatomic, copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter; 176 | 177 | /** 178 | * Returns global SDWebImageManager instance. 179 | * 180 | * @return SDWebImageManager shared instance 181 | */ 182 | + (SDWebImageManager *)sharedManager; 183 | 184 | /** 185 | * Allows to specify instance of cache and image downloader used with image manager. 186 | * @return new instance of `SDWebImageManager` with specified cache and downloader. 187 | */ 188 | - (instancetype)initWithCache:(SDImageCache *)cache downloader:(SDWebImageDownloader *)downloader; 189 | 190 | /** 191 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 192 | * 193 | * @param url The URL to the image 194 | * @param options A mask to specify options to use for this request 195 | * @param progressBlock A block called while image is downloading 196 | * @param completedBlock A block called when operation has been completed. 197 | * 198 | * This parameter is required. 199 | * 200 | * This block has no return value and takes the requested UIImage as first parameter. 201 | * In case of error the image parameter is nil and the second parameter may contain an NSError. 202 | * 203 | * The third parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache 204 | * or from the memory cache or from the network. 205 | * 206 | * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is 207 | * downloading. This block is thus called repeatedly with a partial image. When image is fully downloaded, the 208 | * block is called a last time with the full image and the last parameter set to YES. 209 | * 210 | * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation 211 | */ 212 | - (id )downloadImageWithURL:(NSURL *)url 213 | options:(SDWebImageOptions)options 214 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 215 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock; 216 | 217 | /** 218 | * Saves image to cache for given URL 219 | * 220 | * @param image The image to cache 221 | * @param url The URL to the image 222 | * 223 | */ 224 | 225 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url; 226 | 227 | /** 228 | * Cancel all current operations 229 | */ 230 | - (void)cancelAll; 231 | 232 | /** 233 | * Check one or more operations running 234 | */ 235 | - (BOOL)isRunning; 236 | 237 | /** 238 | * Check if image has already been cached 239 | * 240 | * @param url image url 241 | * 242 | * @return if the image was already cached 243 | */ 244 | - (BOOL)cachedImageExistsForURL:(NSURL *)url; 245 | 246 | /** 247 | * Check if image has already been cached on disk only 248 | * 249 | * @param url image url 250 | * 251 | * @return if the image was already cached (disk only) 252 | */ 253 | - (BOOL)diskImageExistsForURL:(NSURL *)url; 254 | 255 | /** 256 | * Async check if image has already been cached 257 | * 258 | * @param url image url 259 | * @param completionBlock the block to be executed when the check is finished 260 | * 261 | * @note the completion block is always executed on the main queue 262 | */ 263 | - (void)cachedImageExistsForURL:(NSURL *)url 264 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 265 | 266 | /** 267 | * Async check if image has already been cached on disk only 268 | * 269 | * @param url image url 270 | * @param completionBlock the block to be executed when the check is finished 271 | * 272 | * @note the completion block is always executed on the main queue 273 | */ 274 | - (void)diskImageExistsForURL:(NSURL *)url 275 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 276 | 277 | 278 | /** 279 | *Return the cache key for a given URL 280 | */ 281 | - (NSString *)cacheKeyForURL:(NSURL *)url; 282 | 283 | @end 284 | 285 | 286 | #pragma mark - Deprecated 287 | 288 | typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionBlock`"); 289 | typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionWithFinishedBlock`"); 290 | 291 | 292 | @interface SDWebImageManager (Deprecated) 293 | 294 | /** 295 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 296 | * 297 | * @deprecated This method has been deprecated. Use `downloadImageWithURL:options:progress:completed:` 298 | */ 299 | - (id )downloadWithURL:(NSURL *)url 300 | options:(SDWebImageOptions)options 301 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 302 | completed:(SDWebImageCompletedWithFinishedBlock)completedBlock __deprecated_msg("Method deprecated. Use `downloadImageWithURL:options:progress:completed:`"); 303 | 304 | @end 305 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/SDWebImageOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | 11 | @protocol SDWebImageOperation 12 | 13 | - (void)cancel; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/SDWebImagePrefetcher.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageManager.h" 11 | 12 | @class SDWebImagePrefetcher; 13 | 14 | @protocol SDWebImagePrefetcherDelegate 15 | 16 | @optional 17 | 18 | /** 19 | * Called when an image was prefetched. 20 | * 21 | * @param imagePrefetcher The current image prefetcher 22 | * @param imageURL The image url that was prefetched 23 | * @param finishedCount The total number of images that were prefetched (successful or not) 24 | * @param totalCount The total number of images that were to be prefetched 25 | */ 26 | - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; 27 | 28 | /** 29 | * Called when all images are prefetched. 30 | * @param imagePrefetcher The current image prefetcher 31 | * @param totalCount The total number of images that were prefetched (whether successful or not) 32 | * @param skippedCount The total number of images that were skipped 33 | */ 34 | - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; 35 | 36 | @end 37 | 38 | typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); 39 | typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); 40 | 41 | /** 42 | * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. 43 | */ 44 | @interface SDWebImagePrefetcher : NSObject 45 | 46 | /** 47 | * The web image manager 48 | */ 49 | @property (strong, nonatomic, readonly) SDWebImageManager *manager; 50 | 51 | /** 52 | * Maximum number of URLs to prefetch at the same time. Defaults to 3. 53 | */ 54 | @property (nonatomic, assign) NSUInteger maxConcurrentDownloads; 55 | 56 | /** 57 | * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. 58 | */ 59 | @property (nonatomic, assign) SDWebImageOptions options; 60 | 61 | /** 62 | * Queue options for Prefetcher. Defaults to Main Queue. 63 | */ 64 | @property (nonatomic, assign) dispatch_queue_t prefetcherQueue; 65 | 66 | @property (weak, nonatomic) id delegate; 67 | 68 | /** 69 | * Return the global image prefetcher instance. 70 | */ 71 | + (SDWebImagePrefetcher *)sharedImagePrefetcher; 72 | 73 | /** 74 | * Allows you to instantiate a prefetcher with any arbitrary image manager. 75 | */ 76 | - (id)initWithImageManager:(SDWebImageManager *)manager; 77 | 78 | /** 79 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 80 | * currently one image is downloaded at a time, 81 | * and skips images for failed downloads and proceed to the next image in the list 82 | * 83 | * @param urls list of URLs to prefetch 84 | */ 85 | - (void)prefetchURLs:(NSArray *)urls; 86 | 87 | /** 88 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 89 | * currently one image is downloaded at a time, 90 | * and skips images for failed downloads and proceed to the next image in the list 91 | * 92 | * @param urls list of URLs to prefetch 93 | * @param progressBlock block to be called when progress updates; 94 | * first parameter is the number of completed (successful or not) requests, 95 | * second parameter is the total number of images originally requested to be prefetched 96 | * @param completionBlock block to be called when prefetching is completed 97 | * first param is the number of completed (successful or not) requests, 98 | * second parameter is the number of skipped requests 99 | */ 100 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock; 101 | 102 | /** 103 | * Remove and cancel queued list 104 | */ 105 | - (void)cancelPrefetching; 106 | 107 | 108 | @end 109 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/SDWebImagePrefetcher.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImagePrefetcher.h" 10 | 11 | @interface SDWebImagePrefetcher () 12 | 13 | @property (strong, nonatomic) SDWebImageManager *manager; 14 | @property (strong, nonatomic) NSArray *prefetchURLs; 15 | @property (assign, nonatomic) NSUInteger requestedCount; 16 | @property (assign, nonatomic) NSUInteger skippedCount; 17 | @property (assign, nonatomic) NSUInteger finishedCount; 18 | @property (assign, nonatomic) NSTimeInterval startedTime; 19 | @property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock; 20 | @property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock; 21 | 22 | @end 23 | 24 | @implementation SDWebImagePrefetcher 25 | 26 | + (SDWebImagePrefetcher *)sharedImagePrefetcher { 27 | static dispatch_once_t once; 28 | static id instance; 29 | dispatch_once(&once, ^{ 30 | instance = [self new]; 31 | }); 32 | return instance; 33 | } 34 | 35 | - (id)init { 36 | return [self initWithImageManager:[SDWebImageManager new]]; 37 | } 38 | 39 | - (id)initWithImageManager:(SDWebImageManager *)manager { 40 | if ((self = [super init])) { 41 | _manager = manager; 42 | _options = SDWebImageLowPriority; 43 | _prefetcherQueue = dispatch_get_main_queue(); 44 | self.maxConcurrentDownloads = 3; 45 | } 46 | return self; 47 | } 48 | 49 | - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { 50 | self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; 51 | } 52 | 53 | - (NSUInteger)maxConcurrentDownloads { 54 | return self.manager.imageDownloader.maxConcurrentDownloads; 55 | } 56 | 57 | - (void)startPrefetchingAtIndex:(NSUInteger)index { 58 | if (index >= self.prefetchURLs.count) return; 59 | self.requestedCount++; 60 | [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 61 | if (!finished) return; 62 | self.finishedCount++; 63 | 64 | if (image) { 65 | if (self.progressBlock) { 66 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 67 | } 68 | } 69 | else { 70 | if (self.progressBlock) { 71 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 72 | } 73 | // Add last failed 74 | self.skippedCount++; 75 | } 76 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { 77 | [self.delegate imagePrefetcher:self 78 | didPrefetchURL:self.prefetchURLs[index] 79 | finishedCount:self.finishedCount 80 | totalCount:self.prefetchURLs.count 81 | ]; 82 | } 83 | if (self.prefetchURLs.count > self.requestedCount) { 84 | dispatch_async(self.prefetcherQueue, ^{ 85 | [self startPrefetchingAtIndex:self.requestedCount]; 86 | }); 87 | } else if (self.finishedCount == self.requestedCount) { 88 | [self reportStatus]; 89 | if (self.completionBlock) { 90 | self.completionBlock(self.finishedCount, self.skippedCount); 91 | self.completionBlock = nil; 92 | } 93 | self.progressBlock = nil; 94 | } 95 | }]; 96 | } 97 | 98 | - (void)reportStatus { 99 | NSUInteger total = [self.prefetchURLs count]; 100 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { 101 | [self.delegate imagePrefetcher:self 102 | didFinishWithTotalCount:(total - self.skippedCount) 103 | skippedCount:self.skippedCount 104 | ]; 105 | } 106 | } 107 | 108 | - (void)prefetchURLs:(NSArray *)urls { 109 | [self prefetchURLs:urls progress:nil completed:nil]; 110 | } 111 | 112 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock { 113 | [self cancelPrefetching]; // Prevent duplicate prefetch request 114 | self.startedTime = CFAbsoluteTimeGetCurrent(); 115 | self.prefetchURLs = urls; 116 | self.completionBlock = completionBlock; 117 | self.progressBlock = progressBlock; 118 | 119 | if (urls.count == 0) { 120 | if (completionBlock) { 121 | completionBlock(0,0); 122 | } 123 | } else { 124 | // Starts prefetching from the very first image on the list with the max allowed concurrency 125 | NSUInteger listCount = self.prefetchURLs.count; 126 | for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { 127 | [self startPrefetchingAtIndex:i]; 128 | } 129 | } 130 | } 131 | 132 | - (void)cancelPrefetching { 133 | self.prefetchURLs = nil; 134 | self.skippedCount = 0; 135 | self.requestedCount = 0; 136 | self.finishedCount = 0; 137 | [self.manager cancelAll]; 138 | } 139 | 140 | @end 141 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/UIButton+WebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIButton+WebCache.h" 10 | #import "objc/runtime.h" 11 | #import "UIView+WebCacheOperation.h" 12 | 13 | static char imageURLStorageKey; 14 | 15 | @implementation UIButton (WebCache) 16 | 17 | - (NSURL *)sd_currentImageURL { 18 | NSURL *url = self.imageURLStorage[@(self.state)]; 19 | 20 | if (!url) { 21 | url = self.imageURLStorage[@(UIControlStateNormal)]; 22 | } 23 | 24 | return url; 25 | } 26 | 27 | - (NSURL *)sd_imageURLForState:(UIControlState)state { 28 | return self.imageURLStorage[@(state)]; 29 | } 30 | 31 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state { 32 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 33 | } 34 | 35 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { 36 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 37 | } 38 | 39 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 40 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 41 | } 42 | 43 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock { 44 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; 45 | } 46 | 47 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 48 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; 49 | } 50 | 51 | - (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 52 | 53 | [self setImage:placeholder forState:state]; 54 | [self sd_cancelImageLoadForState:state]; 55 | 56 | if (!url) { 57 | [self.imageURLStorage removeObjectForKey:@(state)]; 58 | 59 | dispatch_main_async_safe(^{ 60 | if (completedBlock) { 61 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 62 | completedBlock(nil, error, SDImageCacheTypeNone, url); 63 | } 64 | }); 65 | 66 | return; 67 | } 68 | 69 | self.imageURLStorage[@(state)] = url; 70 | 71 | __weak __typeof(self)wself = self; 72 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 73 | if (!wself) return; 74 | dispatch_main_sync_safe(^{ 75 | __strong UIButton *sself = wself; 76 | if (!sself) return; 77 | if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) 78 | { 79 | completedBlock(image, error, cacheType, url); 80 | return; 81 | } 82 | else if (image) { 83 | [sself setImage:image forState:state]; 84 | } 85 | if (completedBlock && finished) { 86 | completedBlock(image, error, cacheType, url); 87 | } 88 | }); 89 | }]; 90 | [self sd_setImageLoadOperation:operation forState:state]; 91 | } 92 | 93 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { 94 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 95 | } 96 | 97 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { 98 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 99 | } 100 | 101 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 102 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 103 | } 104 | 105 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock { 106 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; 107 | } 108 | 109 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 110 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; 111 | } 112 | 113 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 114 | [self sd_cancelBackgroundImageLoadForState:state]; 115 | 116 | [self setBackgroundImage:placeholder forState:state]; 117 | 118 | if (url) { 119 | __weak __typeof(self)wself = self; 120 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 121 | if (!wself) return; 122 | dispatch_main_sync_safe(^{ 123 | __strong UIButton *sself = wself; 124 | if (!sself) return; 125 | if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) 126 | { 127 | completedBlock(image, error, cacheType, url); 128 | return; 129 | } 130 | else if (image) { 131 | [sself setBackgroundImage:image forState:state]; 132 | } 133 | if (completedBlock && finished) { 134 | completedBlock(image, error, cacheType, url); 135 | } 136 | }); 137 | }]; 138 | [self sd_setBackgroundImageLoadOperation:operation forState:state]; 139 | } else { 140 | dispatch_main_async_safe(^{ 141 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 142 | if (completedBlock) { 143 | completedBlock(nil, error, SDImageCacheTypeNone, url); 144 | } 145 | }); 146 | } 147 | } 148 | 149 | - (void)sd_setImageLoadOperation:(id)operation forState:(UIControlState)state { 150 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 151 | } 152 | 153 | - (void)sd_cancelImageLoadForState:(UIControlState)state { 154 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 155 | } 156 | 157 | - (void)sd_setBackgroundImageLoadOperation:(id)operation forState:(UIControlState)state { 158 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 159 | } 160 | 161 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { 162 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 163 | } 164 | 165 | - (NSMutableDictionary *)imageURLStorage { 166 | NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey); 167 | if (!storage) 168 | { 169 | storage = [NSMutableDictionary dictionary]; 170 | objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 171 | } 172 | 173 | return storage; 174 | } 175 | 176 | @end 177 | 178 | 179 | @implementation UIButton (WebCacheDeprecated) 180 | 181 | - (NSURL *)currentImageURL { 182 | return [self sd_currentImageURL]; 183 | } 184 | 185 | - (NSURL *)imageURLForState:(UIControlState)state { 186 | return [self sd_imageURLForState:state]; 187 | } 188 | 189 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state { 190 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 191 | } 192 | 193 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { 194 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 195 | } 196 | 197 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 198 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 199 | } 200 | 201 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { 202 | [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 203 | if (completedBlock) { 204 | completedBlock(image, error, cacheType); 205 | } 206 | }]; 207 | } 208 | 209 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { 210 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 211 | if (completedBlock) { 212 | completedBlock(image, error, cacheType); 213 | } 214 | }]; 215 | } 216 | 217 | - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 218 | [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 219 | if (completedBlock) { 220 | completedBlock(image, error, cacheType); 221 | } 222 | }]; 223 | } 224 | 225 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { 226 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 227 | } 228 | 229 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { 230 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 231 | } 232 | 233 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 234 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 235 | } 236 | 237 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock { 238 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 239 | if (completedBlock) { 240 | completedBlock(image, error, cacheType); 241 | } 242 | }]; 243 | } 244 | 245 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { 246 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 247 | if (completedBlock) { 248 | completedBlock(image, error, cacheType); 249 | } 250 | }]; 251 | } 252 | 253 | - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 254 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 255 | if (completedBlock) { 256 | completedBlock(image, error, cacheType); 257 | } 258 | }]; 259 | } 260 | 261 | - (void)cancelCurrentImageLoad { 262 | // in a backwards compatible manner, cancel for current state 263 | [self sd_cancelImageLoadForState:self.state]; 264 | } 265 | 266 | - (void)cancelBackgroundImageLoadForState:(UIControlState)state { 267 | [self sd_cancelBackgroundImageLoadForState:state]; 268 | } 269 | 270 | @end 271 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/UIImage+GIF.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+GIF.h 3 | // LBGIFImage 4 | // 5 | // Created by Laurin Brandner on 06.01.12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface UIImage (GIF) 12 | 13 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name; 14 | 15 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data; 16 | 17 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/UIImage+GIF.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+GIF.m 3 | // LBGIFImage 4 | // 5 | // Created by Laurin Brandner on 06.01.12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "UIImage+GIF.h" 10 | #import 11 | 12 | @implementation UIImage (GIF) 13 | 14 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data { 15 | if (!data) { 16 | return nil; 17 | } 18 | 19 | CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); 20 | 21 | size_t count = CGImageSourceGetCount(source); 22 | 23 | UIImage *animatedImage; 24 | 25 | if (count <= 1) { 26 | animatedImage = [[UIImage alloc] initWithData:data]; 27 | } 28 | else { 29 | NSMutableArray *images = [NSMutableArray array]; 30 | 31 | NSTimeInterval duration = 0.0f; 32 | 33 | for (size_t i = 0; i < count; i++) { 34 | CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL); 35 | if (!image) { 36 | continue; 37 | } 38 | 39 | duration += [self sd_frameDurationAtIndex:i source:source]; 40 | 41 | [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; 42 | 43 | CGImageRelease(image); 44 | } 45 | 46 | if (!duration) { 47 | duration = (1.0f / 10.0f) * count; 48 | } 49 | 50 | animatedImage = [UIImage animatedImageWithImages:images duration:duration]; 51 | } 52 | 53 | CFRelease(source); 54 | 55 | return animatedImage; 56 | } 57 | 58 | + (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { 59 | float frameDuration = 0.1f; 60 | CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); 61 | NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; 62 | NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; 63 | 64 | NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; 65 | if (delayTimeUnclampedProp) { 66 | frameDuration = [delayTimeUnclampedProp floatValue]; 67 | } 68 | else { 69 | 70 | NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; 71 | if (delayTimeProp) { 72 | frameDuration = [delayTimeProp floatValue]; 73 | } 74 | } 75 | 76 | // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. 77 | // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify 78 | // a duration of <= 10 ms. See and 79 | // for more information. 80 | 81 | if (frameDuration < 0.011f) { 82 | frameDuration = 0.100f; 83 | } 84 | 85 | CFRelease(cfFrameProperties); 86 | return frameDuration; 87 | } 88 | 89 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name { 90 | CGFloat scale = [UIScreen mainScreen].scale; 91 | 92 | if (scale > 1.0f) { 93 | NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"]; 94 | 95 | NSData *data = [NSData dataWithContentsOfFile:retinaPath]; 96 | 97 | if (data) { 98 | return [UIImage sd_animatedGIFWithData:data]; 99 | } 100 | 101 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 102 | 103 | data = [NSData dataWithContentsOfFile:path]; 104 | 105 | if (data) { 106 | return [UIImage sd_animatedGIFWithData:data]; 107 | } 108 | 109 | return [UIImage imageNamed:name]; 110 | } 111 | else { 112 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 113 | 114 | NSData *data = [NSData dataWithContentsOfFile:path]; 115 | 116 | if (data) { 117 | return [UIImage sd_animatedGIFWithData:data]; 118 | } 119 | 120 | return [UIImage imageNamed:name]; 121 | } 122 | } 123 | 124 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size { 125 | if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) { 126 | return self; 127 | } 128 | 129 | CGSize scaledSize = size; 130 | CGPoint thumbnailPoint = CGPointZero; 131 | 132 | CGFloat widthFactor = size.width / self.size.width; 133 | CGFloat heightFactor = size.height / self.size.height; 134 | CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor; 135 | scaledSize.width = self.size.width * scaleFactor; 136 | scaledSize.height = self.size.height * scaleFactor; 137 | 138 | if (widthFactor > heightFactor) { 139 | thumbnailPoint.y = (size.height - scaledSize.height) * 0.5; 140 | } 141 | else if (widthFactor < heightFactor) { 142 | thumbnailPoint.x = (size.width - scaledSize.width) * 0.5; 143 | } 144 | 145 | NSMutableArray *scaledImages = [NSMutableArray array]; 146 | 147 | for (UIImage *image in self.images) { 148 | UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); 149 | 150 | [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)]; 151 | UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 152 | 153 | [scaledImages addObject:newImage]; 154 | 155 | UIGraphicsEndImageContext(); 156 | } 157 | 158 | return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; 159 | } 160 | 161 | @end 162 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/UIImage+MultiFormat.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+MultiFormat.h 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface UIImage (MultiFormat) 12 | 13 | + (UIImage *)sd_imageWithData:(NSData *)data; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/UIImage+MultiFormat.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+MultiFormat.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "UIImage+MultiFormat.h" 10 | #import "UIImage+GIF.h" 11 | #import "NSData+ImageContentType.h" 12 | #import 13 | 14 | #ifdef SD_WEBP 15 | #import "UIImage+WebP.h" 16 | #endif 17 | 18 | @implementation UIImage (MultiFormat) 19 | 20 | + (UIImage *)sd_imageWithData:(NSData *)data { 21 | if (!data) { 22 | return nil; 23 | } 24 | 25 | UIImage *image; 26 | NSString *imageContentType = [NSData sd_contentTypeForImageData:data]; 27 | if ([imageContentType isEqualToString:@"image/gif"]) { 28 | image = [UIImage sd_animatedGIFWithData:data]; 29 | } 30 | #ifdef SD_WEBP 31 | else if ([imageContentType isEqualToString:@"image/webp"]) 32 | { 33 | image = [UIImage sd_imageWithWebPData:data]; 34 | } 35 | #endif 36 | else { 37 | image = [[UIImage alloc] initWithData:data]; 38 | UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; 39 | if (orientation != UIImageOrientationUp) { 40 | image = [UIImage imageWithCGImage:image.CGImage 41 | scale:image.scale 42 | orientation:orientation]; 43 | } 44 | } 45 | 46 | 47 | return image; 48 | } 49 | 50 | 51 | +(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData { 52 | UIImageOrientation result = UIImageOrientationUp; 53 | CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); 54 | if (imageSource) { 55 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); 56 | if (properties) { 57 | CFTypeRef val; 58 | int exifOrientation; 59 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); 60 | if (val) { 61 | CFNumberGetValue(val, kCFNumberIntType, &exifOrientation); 62 | result = [self sd_exifOrientationToiOSOrientation:exifOrientation]; 63 | } // else - if it's not set it remains at up 64 | CFRelease((CFTypeRef) properties); 65 | } else { 66 | //NSLog(@"NO PROPERTIES, FAIL"); 67 | } 68 | CFRelease(imageSource); 69 | } 70 | return result; 71 | } 72 | 73 | #pragma mark EXIF orientation tag converter 74 | // Convert an EXIF image orientation to an iOS one. 75 | // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html 76 | + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation { 77 | UIImageOrientation orientation = UIImageOrientationUp; 78 | switch (exifOrientation) { 79 | case 1: 80 | orientation = UIImageOrientationUp; 81 | break; 82 | 83 | case 3: 84 | orientation = UIImageOrientationDown; 85 | break; 86 | 87 | case 8: 88 | orientation = UIImageOrientationLeft; 89 | break; 90 | 91 | case 6: 92 | orientation = UIImageOrientationRight; 93 | break; 94 | 95 | case 2: 96 | orientation = UIImageOrientationUpMirrored; 97 | break; 98 | 99 | case 4: 100 | orientation = UIImageOrientationDownMirrored; 101 | break; 102 | 103 | case 5: 104 | orientation = UIImageOrientationLeftMirrored; 105 | break; 106 | 107 | case 7: 108 | orientation = UIImageOrientationRightMirrored; 109 | break; 110 | default: 111 | break; 112 | } 113 | return orientation; 114 | } 115 | 116 | 117 | 118 | @end 119 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/UIImageView+HighlightedWebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | #import "SDWebImageManager.h" 12 | 13 | /** 14 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state. 15 | */ 16 | @interface UIImageView (HighlightedWebCache) 17 | 18 | /** 19 | * Set the imageView `highlightedImage` with an `url`. 20 | * 21 | * The download is asynchronous and cached. 22 | * 23 | * @param url The url for the image. 24 | */ 25 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url; 26 | 27 | /** 28 | * Set the imageView `highlightedImage` with an `url` and custom options. 29 | * 30 | * The download is asynchronous and cached. 31 | * 32 | * @param url The url for the image. 33 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 34 | */ 35 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options; 36 | 37 | /** 38 | * Set the imageView `highlightedImage` with an `url`. 39 | * 40 | * The download is asynchronous and cached. 41 | * 42 | * @param url The url for the image. 43 | * @param completedBlock A block called when operation has been completed. This block has no return value 44 | * and takes the requested UIImage as first parameter. In case of error the image parameter 45 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 46 | * indicating if the image was retrieved from the local cache or from the network. 47 | * The fourth parameter is the original image url. 48 | */ 49 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; 50 | 51 | /** 52 | * Set the imageView `highlightedImage` with an `url` and custom options. 53 | * 54 | * The download is asynchronous and cached. 55 | * 56 | * @param url The url for the image. 57 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 58 | * @param completedBlock A block called when operation has been completed. This block has no return value 59 | * and takes the requested UIImage as first parameter. In case of error the image parameter 60 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 61 | * indicating if the image was retrieved from the local cache or from the network. 62 | * The fourth parameter is the original image url. 63 | */ 64 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; 65 | 66 | /** 67 | * Set the imageView `highlightedImage` with an `url` and custom options. 68 | * 69 | * The download is asynchronous and cached. 70 | * 71 | * @param url The url for the image. 72 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 73 | * @param progressBlock A block called while image is downloading 74 | * @param completedBlock A block called when operation has been completed. This block has no return value 75 | * and takes the requested UIImage as first parameter. In case of error the image parameter 76 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 77 | * indicating if the image was retrieved from the local cache or from the network. 78 | * The fourth parameter is the original image url. 79 | */ 80 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; 81 | 82 | /** 83 | * Cancel the current download 84 | */ 85 | - (void)sd_cancelCurrentHighlightedImageLoad; 86 | 87 | @end 88 | 89 | 90 | @interface UIImageView (HighlightedWebCacheDeprecated) 91 | 92 | - (void)setHighlightedImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:`"); 93 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:`"); 94 | - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:completed:`"); 95 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:completed:`"); 96 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:progress:completed:`"); 97 | 98 | - (void)cancelCurrentHighlightedImageLoad __deprecated_msg("Use `sd_cancelCurrentHighlightedImageLoad`"); 99 | 100 | @end 101 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/UIImageView+HighlightedWebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIImageView+HighlightedWebCache.h" 10 | #import "UIView+WebCacheOperation.h" 11 | 12 | #define UIImageViewHighlightedWebCacheOperationKey @"highlightedImage" 13 | 14 | @implementation UIImageView (HighlightedWebCache) 15 | 16 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url { 17 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; 18 | } 19 | 20 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { 21 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; 22 | } 23 | 24 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 25 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock]; 26 | } 27 | 28 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 29 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock]; 30 | } 31 | 32 | - (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 33 | [self sd_cancelCurrentHighlightedImageLoad]; 34 | 35 | if (url) { 36 | __weak __typeof(self)wself = self; 37 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 38 | if (!wself) return; 39 | dispatch_main_sync_safe (^ 40 | { 41 | if (!wself) return; 42 | if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) 43 | { 44 | completedBlock(image, error, cacheType, url); 45 | return; 46 | } 47 | else if (image) { 48 | wself.highlightedImage = image; 49 | [wself setNeedsLayout]; 50 | } 51 | if (completedBlock && finished) { 52 | completedBlock(image, error, cacheType, url); 53 | } 54 | }); 55 | }]; 56 | [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey]; 57 | } else { 58 | dispatch_main_async_safe(^{ 59 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 60 | if (completedBlock) { 61 | completedBlock(nil, error, SDImageCacheTypeNone, url); 62 | } 63 | }); 64 | } 65 | } 66 | 67 | - (void)sd_cancelCurrentHighlightedImageLoad { 68 | [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey]; 69 | } 70 | 71 | @end 72 | 73 | 74 | @implementation UIImageView (HighlightedWebCacheDeprecated) 75 | 76 | - (void)setHighlightedImageWithURL:(NSURL *)url { 77 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; 78 | } 79 | 80 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options { 81 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; 82 | } 83 | 84 | - (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { 85 | [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 86 | if (completedBlock) { 87 | completedBlock(image, error, cacheType); 88 | } 89 | }]; 90 | } 91 | 92 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 93 | [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 94 | if (completedBlock) { 95 | completedBlock(image, error, cacheType); 96 | } 97 | }]; 98 | } 99 | 100 | - (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { 101 | [self sd_setHighlightedImageWithURL:url options:0 progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 102 | if (completedBlock) { 103 | completedBlock(image, error, cacheType); 104 | } 105 | }]; 106 | } 107 | 108 | - (void)cancelCurrentHighlightedImageLoad { 109 | [self sd_cancelCurrentHighlightedImageLoad]; 110 | } 111 | 112 | @end 113 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/UIImageView+WebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | #import "SDWebImageManager.h" 11 | 12 | /** 13 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView. 14 | * 15 | * Usage with a UITableViewCell sub-class: 16 | * 17 | * @code 18 | 19 | #import 20 | 21 | ... 22 | 23 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 24 | { 25 | static NSString *MyIdentifier = @"MyIdentifier"; 26 | 27 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 28 | 29 | if (cell == nil) { 30 | cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] 31 | autorelease]; 32 | } 33 | 34 | // Here we use the provided sd_setImageWithURL: method to load the web image 35 | // Ensure you use a placeholder image otherwise cells will be initialized with no image 36 | [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] 37 | placeholderImage:[UIImage imageNamed:@"placeholder"]]; 38 | 39 | cell.textLabel.text = @"My Text"; 40 | return cell; 41 | } 42 | 43 | * @endcode 44 | */ 45 | @interface UIImageView (WebCache) 46 | 47 | /** 48 | * Get the current image URL. 49 | * 50 | * Note that because of the limitations of categories this property can get out of sync 51 | * if you use sd_setImage: directly. 52 | */ 53 | - (NSURL *)sd_imageURL; 54 | 55 | /** 56 | * Set the imageView `image` with an `url`. 57 | * 58 | * The download is asynchronous and cached. 59 | * 60 | * @param url The url for the image. 61 | */ 62 | - (void)sd_setImageWithURL:(NSURL *)url; 63 | 64 | /** 65 | * Set the imageView `image` with an `url` and a placeholder. 66 | * 67 | * The download is asynchronous and cached. 68 | * 69 | * @param url The url for the image. 70 | * @param placeholder The image to be set initially, until the image request finishes. 71 | * @see sd_setImageWithURL:placeholderImage:options: 72 | */ 73 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; 74 | 75 | /** 76 | * Set the imageView `image` with an `url`, placeholder and custom options. 77 | * 78 | * The download is asynchronous and cached. 79 | * 80 | * @param url The url for the image. 81 | * @param placeholder The image to be set initially, until the image request finishes. 82 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 83 | */ 84 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; 85 | 86 | /** 87 | * Set the imageView `image` with an `url`. 88 | * 89 | * The download is asynchronous and cached. 90 | * 91 | * @param url The url for the image. 92 | * @param completedBlock A block called when operation has been completed. This block has no return value 93 | * and takes the requested UIImage as first parameter. In case of error the image parameter 94 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 95 | * indicating if the image was retrieved from the local cache or from the network. 96 | * The fourth parameter is the original image url. 97 | */ 98 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; 99 | 100 | /** 101 | * Set the imageView `image` with an `url`, placeholder. 102 | * 103 | * The download is asynchronous and cached. 104 | * 105 | * @param url The url for the image. 106 | * @param placeholder The image to be set initially, until the image request finishes. 107 | * @param completedBlock A block called when operation has been completed. This block has no return value 108 | * and takes the requested UIImage as first parameter. In case of error the image parameter 109 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 110 | * indicating if the image was retrieved from the local cache or from the network. 111 | * The fourth parameter is the original image url. 112 | */ 113 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; 114 | 115 | /** 116 | * Set the imageView `image` with an `url`, placeholder and custom options. 117 | * 118 | * The download is asynchronous and cached. 119 | * 120 | * @param url The url for the image. 121 | * @param placeholder The image to be set initially, until the image request finishes. 122 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 123 | * @param completedBlock A block called when operation has been completed. This block has no return value 124 | * and takes the requested UIImage as first parameter. In case of error the image parameter 125 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 126 | * indicating if the image was retrieved from the local cache or from the network. 127 | * The fourth parameter is the original image url. 128 | */ 129 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; 130 | 131 | /** 132 | * Set the imageView `image` with an `url`, placeholder and custom options. 133 | * 134 | * The download is asynchronous and cached. 135 | * 136 | * @param url The url for the image. 137 | * @param placeholder The image to be set initially, until the image request finishes. 138 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 139 | * @param progressBlock A block called while image is downloading 140 | * @param completedBlock A block called when operation has been completed. This block has no return value 141 | * and takes the requested UIImage as first parameter. In case of error the image parameter 142 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 143 | * indicating if the image was retrieved from the local cache or from the network. 144 | * The fourth parameter is the original image url. 145 | */ 146 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; 147 | 148 | /** 149 | * Set the imageView `image` with an `url` and optionally a placeholder image. 150 | * 151 | * The download is asynchronous and cached. 152 | * 153 | * @param url The url for the image. 154 | * @param placeholder The image to be set initially, until the image request finishes. 155 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 156 | * @param progressBlock A block called while image is downloading 157 | * @param completedBlock A block called when operation has been completed. This block has no return value 158 | * and takes the requested UIImage as first parameter. In case of error the image parameter 159 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 160 | * indicating if the image was retrieved from the local cache or from the network. 161 | * The fourth parameter is the original image url. 162 | */ 163 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; 164 | 165 | /** 166 | * Download an array of images and starts them in an animation loop 167 | * 168 | * @param arrayOfURLs An array of NSURL 169 | */ 170 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs; 171 | 172 | /** 173 | * Cancel the current download 174 | */ 175 | - (void)sd_cancelCurrentImageLoad; 176 | 177 | - (void)sd_cancelCurrentAnimationImagesLoad; 178 | 179 | /** 180 | * Show activity UIActivityIndicatorView 181 | */ 182 | - (void)setShowActivityIndicatorView:(BOOL)show; 183 | 184 | /** 185 | * set desired UIActivityIndicatorViewStyle 186 | * 187 | * @param style The style of the UIActivityIndicatorView 188 | */ 189 | - (void)setIndicatorStyle:(UIActivityIndicatorViewStyle)style; 190 | 191 | @end 192 | 193 | 194 | @interface UIImageView (WebCacheDeprecated) 195 | 196 | - (NSURL *)imageURL __deprecated_msg("Use `sd_imageURL`"); 197 | 198 | - (void)setImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:`"); 199 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:`"); 200 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options`"); 201 | 202 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:completed:`"); 203 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:completed:`"); 204 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:completed:`"); 205 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:progress:completed:`"); 206 | 207 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithPreviousCachedImageWithURL:placeholderImage:options:progress:completed:`"); 208 | 209 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs __deprecated_msg("Use `sd_setAnimationImagesWithURLs:`"); 210 | 211 | - (void)cancelCurrentArrayLoad __deprecated_msg("Use `sd_cancelCurrentAnimationImagesLoad`"); 212 | 213 | - (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelCurrentImageLoad`"); 214 | 215 | @end 216 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/UIImageView+WebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIImageView+WebCache.h" 10 | #import "objc/runtime.h" 11 | #import "UIView+WebCacheOperation.h" 12 | 13 | static char imageURLKey; 14 | static char TAG_ACTIVITY_INDICATOR; 15 | static char TAG_ACTIVITY_STYLE; 16 | static char TAG_ACTIVITY_SHOW; 17 | 18 | @implementation UIImageView (WebCache) 19 | 20 | - (void)sd_setImageWithURL:(NSURL *)url { 21 | [self sd_setImageWithURL:url placeholderImage:nil options:SDWebImageRetryFailed progress:nil completed:nil]; 22 | } 23 | 24 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 25 | [self sd_setImageWithURL:url placeholderImage:placeholder options:SDWebImageRetryFailed progress:nil completed:nil]; 26 | } 27 | 28 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 29 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 30 | } 31 | 32 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 33 | [self sd_setImageWithURL:url placeholderImage:nil options:SDWebImageRetryFailed progress:nil completed:completedBlock]; 34 | } 35 | 36 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 37 | [self sd_setImageWithURL:url placeholderImage:placeholder options:SDWebImageRetryFailed progress:nil completed:completedBlock]; 38 | } 39 | 40 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 41 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; 42 | } 43 | 44 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 45 | [self sd_cancelCurrentImageLoad]; 46 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 47 | 48 | if (!(options & SDWebImageDelayPlaceholder)) { 49 | dispatch_main_async_safe(^{ 50 | self.image = placeholder; 51 | }); 52 | } 53 | 54 | if (url) { 55 | 56 | // check if activityView is enabled or not 57 | if ([self showActivityIndicatorView]) { 58 | [self addActivityIndicator]; 59 | } 60 | 61 | __weak __typeof(self)wself = self; 62 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 63 | [wself removeActivityIndicator]; 64 | if (!wself) return; 65 | dispatch_main_sync_safe(^{ 66 | if (!wself) return; 67 | if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) 68 | { 69 | completedBlock(image, error, cacheType, url); 70 | return; 71 | } 72 | else if (image) { 73 | wself.image = image; 74 | [wself setNeedsLayout]; 75 | } else { 76 | if ((options & SDWebImageDelayPlaceholder)) { 77 | wself.image = placeholder; 78 | [wself setNeedsLayout]; 79 | } 80 | } 81 | if (completedBlock && finished) { 82 | completedBlock(image, error, cacheType, url); 83 | } 84 | }); 85 | }]; 86 | [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"]; 87 | } else { 88 | dispatch_main_async_safe(^{ 89 | [self removeActivityIndicator]; 90 | if (completedBlock) { 91 | NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 92 | completedBlock(nil, error, SDImageCacheTypeNone, url); 93 | } 94 | }); 95 | } 96 | } 97 | 98 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 99 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; 100 | UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key]; 101 | 102 | [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; 103 | } 104 | 105 | - (NSURL *)sd_imageURL { 106 | return objc_getAssociatedObject(self, &imageURLKey); 107 | } 108 | 109 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { 110 | [self sd_cancelCurrentAnimationImagesLoad]; 111 | __weak __typeof(self)wself = self; 112 | 113 | NSMutableArray *operationsArray = [[NSMutableArray alloc] init]; 114 | 115 | for (NSURL *logoImageURL in arrayOfURLs) { 116 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 117 | if (!wself) return; 118 | dispatch_main_sync_safe(^{ 119 | __strong UIImageView *sself = wself; 120 | [sself stopAnimating]; 121 | if (sself && image) { 122 | NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; 123 | if (!currentImages) { 124 | currentImages = [[NSMutableArray alloc] init]; 125 | } 126 | [currentImages addObject:image]; 127 | 128 | sself.animationImages = currentImages; 129 | [sself setNeedsLayout]; 130 | } 131 | [sself startAnimating]; 132 | }); 133 | }]; 134 | [operationsArray addObject:operation]; 135 | } 136 | 137 | [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"]; 138 | } 139 | 140 | - (void)sd_cancelCurrentImageLoad { 141 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"]; 142 | } 143 | 144 | - (void)sd_cancelCurrentAnimationImagesLoad { 145 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; 146 | } 147 | 148 | 149 | #pragma mark - 150 | - (UIActivityIndicatorView *)activityIndicator { 151 | return (UIActivityIndicatorView *)objc_getAssociatedObject(self, &TAG_ACTIVITY_INDICATOR); 152 | } 153 | 154 | - (void)setActivityIndicator:(UIActivityIndicatorView *)activityIndicator { 155 | objc_setAssociatedObject(self, &TAG_ACTIVITY_INDICATOR, activityIndicator, OBJC_ASSOCIATION_RETAIN); 156 | } 157 | 158 | - (void)setShowActivityIndicatorView:(BOOL)show{ 159 | objc_setAssociatedObject(self, &TAG_ACTIVITY_SHOW, [NSNumber numberWithBool:show], OBJC_ASSOCIATION_RETAIN); 160 | } 161 | 162 | - (BOOL)showActivityIndicatorView{ 163 | return [objc_getAssociatedObject(self, &TAG_ACTIVITY_SHOW) boolValue]; 164 | } 165 | 166 | - (void)setIndicatorStyle:(UIActivityIndicatorViewStyle)style{ 167 | objc_setAssociatedObject(self, &TAG_ACTIVITY_STYLE, [NSNumber numberWithInt:style], OBJC_ASSOCIATION_RETAIN); 168 | } 169 | 170 | - (int)getIndicatorStyle{ 171 | return [objc_getAssociatedObject(self, &TAG_ACTIVITY_STYLE) intValue]; 172 | } 173 | 174 | - (void)addActivityIndicator { 175 | if (!self.activityIndicator) { 176 | self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:[self getIndicatorStyle]]; 177 | self.activityIndicator.translatesAutoresizingMaskIntoConstraints = NO; 178 | 179 | dispatch_main_async_safe(^{ 180 | [self addSubview:self.activityIndicator]; 181 | 182 | [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator 183 | attribute:NSLayoutAttributeCenterX 184 | relatedBy:NSLayoutRelationEqual 185 | toItem:self 186 | attribute:NSLayoutAttributeCenterX 187 | multiplier:1.0 188 | constant:0.0]]; 189 | [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator 190 | attribute:NSLayoutAttributeCenterY 191 | relatedBy:NSLayoutRelationEqual 192 | toItem:self 193 | attribute:NSLayoutAttributeCenterY 194 | multiplier:1.0 195 | constant:0.0]]; 196 | }); 197 | } 198 | 199 | dispatch_main_async_safe(^{ 200 | [self.activityIndicator startAnimating]; 201 | }); 202 | 203 | } 204 | 205 | - (void)removeActivityIndicator { 206 | if (self.activityIndicator) { 207 | [self.activityIndicator removeFromSuperview]; 208 | self.activityIndicator = nil; 209 | } 210 | } 211 | 212 | @end 213 | 214 | 215 | @implementation UIImageView (WebCacheDeprecated) 216 | 217 | - (NSURL *)imageURL { 218 | return [self sd_imageURL]; 219 | } 220 | 221 | - (void)setImageWithURL:(NSURL *)url { 222 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; 223 | } 224 | 225 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 226 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; 227 | } 228 | 229 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 230 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 231 | } 232 | 233 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { 234 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 235 | if (completedBlock) { 236 | completedBlock(image, error, cacheType); 237 | } 238 | }]; 239 | } 240 | 241 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { 242 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 243 | if (completedBlock) { 244 | completedBlock(image, error, cacheType); 245 | } 246 | }]; 247 | } 248 | 249 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 250 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 251 | if (completedBlock) { 252 | completedBlock(image, error, cacheType); 253 | } 254 | }]; 255 | } 256 | 257 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { 258 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 259 | if (completedBlock) { 260 | completedBlock(image, error, cacheType); 261 | } 262 | }]; 263 | } 264 | 265 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 266 | [self sd_setImageWithPreviousCachedImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:completedBlock]; 267 | } 268 | 269 | - (void)cancelCurrentArrayLoad { 270 | [self sd_cancelCurrentAnimationImagesLoad]; 271 | } 272 | 273 | - (void)cancelCurrentImageLoad { 274 | [self sd_cancelCurrentImageLoad]; 275 | } 276 | 277 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { 278 | [self sd_setAnimationImagesWithURLs:arrayOfURLs]; 279 | } 280 | 281 | @end 282 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/UIView+WebCacheOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageManager.h" 11 | 12 | @interface UIView (WebCacheOperation) 13 | 14 | /** 15 | * Set the image load operation (storage in a UIView based dictionary) 16 | * 17 | * @param operation the operation 18 | * @param key key for storing the operation 19 | */ 20 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key; 21 | 22 | /** 23 | * Cancel all operations for the current UIView and key 24 | * 25 | * @param key key for identifying the operations 26 | */ 27 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key; 28 | 29 | /** 30 | * Just remove the operations corresponding to the current UIView and key without cancelling them 31 | * 32 | * @param key key for identifying the operations 33 | */ 34 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key; 35 | 36 | @end 37 | -------------------------------------------------------------------------------- /3DSource/SDWebImage/UIView+WebCacheOperation.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIView+WebCacheOperation.h" 10 | #import "objc/runtime.h" 11 | 12 | static char loadOperationKey; 13 | 14 | @implementation UIView (WebCacheOperation) 15 | 16 | - (NSMutableDictionary *)operationDictionary { 17 | NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); 18 | if (operations) { 19 | return operations; 20 | } 21 | operations = [NSMutableDictionary dictionary]; 22 | objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 23 | return operations; 24 | } 25 | 26 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key { 27 | [self sd_cancelImageLoadOperationWithKey:key]; 28 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 29 | [operationDictionary setObject:operation forKey:key]; 30 | } 31 | 32 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key { 33 | // Cancel in progress downloader from queue 34 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 35 | id operations = [operationDictionary objectForKey:key]; 36 | if (operations) { 37 | if ([operations isKindOfClass:[NSArray class]]) { 38 | for (id operation in operations) { 39 | if (operation) { 40 | [operation cancel]; 41 | } 42 | } 43 | } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){ 44 | [(id) operations cancel]; 45 | } 46 | [operationDictionary removeObjectForKey:key]; 47 | } 48 | } 49 | 50 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key { 51 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 52 | [operationDictionary removeObjectForKey:key]; 53 | } 54 | 55 | @end 56 | -------------------------------------------------------------------------------- /3DSource/WSImagebroswerVC/WSImageBroserCell.h: -------------------------------------------------------------------------------- 1 | // 2 | // WSImageBroserCell.h 3 | // doucui 4 | // 5 | // Created by 吴振松 on 16/10/12. 6 | // Copyright © 2016年 lootai. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "WSImageModel.h" 11 | 12 | @interface WSImageBroserCell : UICollectionViewCell 13 | @property (nonatomic, strong) WSImageModel *model; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /3DSource/WSImagebroswerVC/WSImageBroserCell.m: -------------------------------------------------------------------------------- 1 | // 2 | // WSImageBroserCell.m 3 | // doucui 4 | // 5 | // Created by 吴振松 on 16/10/12. 6 | // Copyright © 2016年 lootai. All rights reserved. 7 | // 8 | 9 | #import "WSImageBroserCell.h" 10 | #import "UIImageView+WebCache.h" 11 | 12 | @interface WSImageBroserCell() 13 | @property (nonatomic, strong) UIScrollView *scrollView; 14 | @property (nonatomic, strong) UIImageView *imageView; 15 | @end 16 | 17 | @implementation WSImageBroserCell 18 | 19 | - (instancetype)initWithFrame:(CGRect)frame { 20 | if(self = [super initWithFrame:frame]) { 21 | [self setupView]; 22 | } 23 | return self; 24 | } 25 | 26 | - (void)setupView { 27 | _scrollView = [[UIScrollView alloc]initWithFrame:self.bounds]; 28 | _scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; 29 | _scrollView.delegate = self; 30 | _scrollView.minimumZoomScale = 1;//设置最小放大比例 31 | _scrollView.maximumZoomScale = 2.5;//设置最大放大比例 32 | [self addSubview:_scrollView]; 33 | 34 | _imageView = [[UIImageView alloc] initWithFrame:_scrollView.bounds]; 35 | _imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; 36 | _imageView.contentMode = UIViewContentModeScaleAspectFit; 37 | [_scrollView addSubview:_imageView]; 38 | 39 | UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)]; 40 | tap.numberOfTapsRequired = 2; 41 | [self addGestureRecognizer:tap]; 42 | } 43 | 44 | - (void)tap:(UITapGestureRecognizer *)tap { 45 | if(_scrollView.zoomScale != 1) { 46 | [_scrollView setZoomScale:1 animated:YES]; 47 | } 48 | else { 49 | [_scrollView setZoomScale:2.5 animated:YES]; 50 | } 51 | } 52 | 53 | - (void)setModel:(WSImageModel *)model { 54 | _scrollView.zoomScale = 1.0; 55 | _model = model; 56 | if(model.image) { 57 | _imageView.image = model.image; 58 | } 59 | else { 60 | [_imageView sd_setImageWithURL:[NSURL URLWithString:model.imageUrl]]; 61 | } 62 | 63 | } 64 | 65 | -(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView{//两手指触摸放大时调用,返回需要改变的view 66 | return _imageView; 67 | } 68 | 69 | -(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{//结束放大时调用 70 | if (scale < 1.0) {//如果放大比例小于1.0则停止放大后返回原大小 71 | [scrollView setZoomScale:1.0 animated:YES]; 72 | } 73 | } 74 | 75 | 76 | @end 77 | -------------------------------------------------------------------------------- /3DSource/WSImagebroswerVC/WSImageBroswerVC.h: -------------------------------------------------------------------------------- 1 | // 2 | // WSImageBroswerVC.h 3 | // doucui 4 | // 5 | // Created by 吴振松 on 16/10/12. 6 | // Copyright © 2016年 lootai. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "WSImageModel.h" 11 | 12 | @interface WSImageBroswerVC : UIViewController 13 | @property (nonatomic, strong) UICollectionView *collectionView; 14 | 15 | @property (nonatomic, strong) NSMutableArray* imageArray; 16 | @property (nonatomic, assign) NSInteger showIndex; 17 | 18 | - (void)initializeView; 19 | - (void)initializeData; 20 | - (void)refreshTitle; 21 | 22 | @end 23 | 24 | -------------------------------------------------------------------------------- /3DSource/WSImagebroswerVC/WSImageBroswerVC.m: -------------------------------------------------------------------------------- 1 | // 2 | // WSImageBroswerVC.m 3 | // doucui 4 | // 5 | // Created by 吴振松 on 16/10/12. 6 | // Copyright © 2016年 lootai. All rights reserved. 7 | // 8 | 9 | #import "WSImageBroswerVC.h" 10 | #import "WSImageBroserCell.h" 11 | @interface WSImageBroswerVC () 12 | 13 | @end 14 | 15 | @implementation WSImageBroswerVC 16 | 17 | - (void)viewDidLoad { 18 | [super viewDidLoad]; 19 | [self initializeView]; 20 | [self initializeData]; 21 | } 22 | 23 | - (void)initializeView { 24 | self.view.backgroundColor = [UIColor blackColor]; 25 | UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; 26 | layout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height); 27 | layout.minimumLineSpacing = 0.0f; 28 | layout.minimumInteritemSpacing = 0.0f; 29 | layout.scrollDirection = UICollectionViewScrollDirectionHorizontal; 30 | _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout]; 31 | _collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; 32 | _collectionView.showsVerticalScrollIndicator = NO; 33 | _collectionView.showsHorizontalScrollIndicator = NO; 34 | [_collectionView setDelegate:self]; 35 | [_collectionView setDataSource:self]; 36 | _collectionView.pagingEnabled = YES; 37 | _collectionView.backgroundColor = [UIColor clearColor]; 38 | [self.view addSubview:_collectionView]; 39 | 40 | [_collectionView registerClass:[WSImageBroserCell class] forCellWithReuseIdentifier:NSStringFromClass([WSImageBroserCell class])]; 41 | } 42 | 43 | - (void)initializeData { 44 | [self.collectionView reloadData]; 45 | if(_showIndex > 0 && _showIndex < _imageArray.count) { 46 | dispatch_async(dispatch_get_main_queue(), ^{ 47 | [self.collectionView setContentOffset:CGPointMake(_showIndex*self.collectionView.frame.size.width, 0) animated:NO]; 48 | }); 49 | } 50 | else { 51 | [self refreshTitle]; 52 | } 53 | } 54 | 55 | - (void)refreshTitle { 56 | NSInteger index = self.collectionView.contentOffset.x/self.collectionView.frame.size.width; 57 | _showIndex = index; 58 | index += 1; 59 | if(index >= 0 && index <= _imageArray.count) { 60 | self.title = [NSString stringWithFormat:@"%@/%@",@(index),@(_imageArray.count)]; 61 | } 62 | } 63 | 64 | - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { 65 | return _imageArray.count; 66 | } 67 | 68 | - (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 69 | WSImageBroserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([WSImageBroserCell class]) forIndexPath:indexPath]; 70 | if(indexPath.row < _imageArray.count) { 71 | cell.model = _imageArray[indexPath.row]; 72 | } 73 | return cell; 74 | } 75 | 76 | - (void)scrollViewDidScroll:(UIScrollView *)scrollView { 77 | [self refreshTitle]; 78 | } 79 | 80 | - (void)didReceiveMemoryWarning { 81 | [super didReceiveMemoryWarning]; 82 | // Dispose of any resources that can be recreated. 83 | } 84 | 85 | /* 86 | #pragma mark - Navigation 87 | 88 | // In a storyboard-based application, you will often want to do a little preparation before navigation 89 | - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 90 | // Get the new view controller using [segue destinationViewController]. 91 | // Pass the selected object to the new view controller. 92 | } 93 | */ 94 | 95 | @end 96 | -------------------------------------------------------------------------------- /3DSource/WSImagebroswerVC/WSImageModel.h: -------------------------------------------------------------------------------- 1 | // 2 | // WSImageModel.h 3 | // doucui 4 | // 5 | // Created by 吴振松 on 16/10/12. 6 | // Copyright © 2016年 lootai. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | @interface WSImageModel : NSObject 13 | 14 | @property (nonatomic, strong) NSString *imageUrl; 15 | @property (nonatomic, strong) UIImage *image; 16 | 17 | @end 18 | -------------------------------------------------------------------------------- /3DSource/WSImagebroswerVC/WSImageModel.m: -------------------------------------------------------------------------------- 1 | // 2 | // WSImageModel.m 3 | // doucui 4 | // 5 | // Created by 吴振松 on 16/10/12. 6 | // Copyright © 2016年 lootai. All rights reserved. 7 | // 8 | 9 | #import "WSImageModel.h" 10 | 11 | @implementation WSImageModel 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /3DSource/WSImagebroswerVC/WSPhotosBroseVC.h: -------------------------------------------------------------------------------- 1 | // 2 | // GoodsImageBroseVC.h 3 | // doucui 4 | // 5 | // Created by 吴振松 on 16/10/12. 6 | // Copyright © 2016年 lootai. All rights reserved. 7 | // 8 | 9 | #import "WSImageBroswerVC.h" 10 | 11 | @interface WSPhotosBroseVC : WSImageBroswerVC 12 | @property (nonatomic, copy) void(^completion)(NSArray *array); 13 | @end 14 | -------------------------------------------------------------------------------- /3DSource/WSImagebroswerVC/WSPhotosBroseVC.m: -------------------------------------------------------------------------------- 1 | // 2 | // GoodsImageBroseVC.m 3 | // doucui 4 | // 5 | // Created by 吴振松 on 16/10/12. 6 | // Copyright © 2016年 lootai. All rights reserved. 7 | // 8 | 9 | typedef enum { 10 | NavigationBarItemTypeBack, 11 | NavigationBarItemTypeLeft, 12 | NavigationBarItemTypeRight, 13 | } NavigationBarItemType; 14 | 15 | #import "WSPhotosBroseVC.h" 16 | 17 | @implementation WSPhotosBroseVC 18 | 19 | - (void)viewDidLoad { 20 | [super viewDidLoad]; 21 | } 22 | 23 | 24 | - (void)initializeView { 25 | [super initializeView]; 26 | [self setBarButtonWithText:@"删除" target:self action:@selector(onClickDel) type:NavigationBarItemTypeRight]; 27 | [self setBarButtonWithText:@"返回" target:self action:@selector(onClickBack) type:NavigationBarItemTypeLeft]; 28 | } 29 | 30 | -(UIBarButtonItem *)setBarButtonWithText:(NSString*)text 31 | target:(id)target 32 | action:(SEL)action 33 | type:(NavigationBarItemType)type 34 | { 35 | UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom]; 36 | [button.titleLabel setFont:[UIFont systemFontOfSize:14]]; 37 | [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 38 | [button setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted]; 39 | [button setTitle:text forState:UIControlStateNormal]; 40 | [button sizeToFit]; 41 | 42 | [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside]; 43 | 44 | UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; 45 | space.width = -8; 46 | 47 | UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button]; 48 | if (type == NavigationBarItemTypeLeft) { 49 | self.navigationItem.leftBarButtonItems = @[space,buttonItem]; 50 | } 51 | else if(type == NavigationBarItemTypeRight) { 52 | self.navigationItem.rightBarButtonItems = @[space,buttonItem]; 53 | } 54 | else { 55 | self.navigationItem.backBarButtonItem = buttonItem; 56 | } 57 | 58 | return buttonItem; 59 | } 60 | 61 | 62 | - (void)onClickDel { 63 | if(self.showIndex >= 0 && self.showIndex < self.imageArray.count) { 64 | [self.imageArray removeObjectAtIndex:self.showIndex]; 65 | [self.collectionView reloadData]; 66 | } 67 | [self refreshTitle]; 68 | if(self.imageArray.count == 0) { 69 | [self onClickBack]; 70 | } 71 | } 72 | 73 | - (void)onClickBack { 74 | if(self.completion) { 75 | NSMutableArray *array = [NSMutableArray new]; 76 | for (WSImageModel *model in self.imageArray) { 77 | [array addObject:model.image]; 78 | } 79 | self.completion(array); 80 | } 81 | [self.navigationController popViewControllerAnimated:YES]; 82 | } 83 | 84 | @end 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ####**WSImagePicker** 2 | **高性能多选图片库,类似于微信发布朋友圈中 ‘获取相册及拍照’模块** 3 | 4 | ![image](http://ofa0lelax.bkt.clouddn.com/3.png-w320h0) ![image](http://ofa0lelax.bkt.clouddn.com/2.png-w320h0) ![image](http://ofa0lelax.bkt.clouddn.com/1.png-w320h0) 5 | 6 | 获取相册照片部分可以多选,加载速度快,采用JFImagePickerController https://github.com/johnil/JFImagePickerController并在此基础上增加图片数量选取限制; 7 | 点击图片显示大图,并能进行双击放大缩小,双指缩放、删除等操作; 8 | 9 | ####**How to user** 10 | #####**Import** 11 | 12 | #import "WSImagePickerView.h" 13 | 14 | #####**parameter settings** 15 | WSImagePickerConfig *config = [WSImagePickerConfig new]; 16 | config.itemSize = CGSizeMake(70, 70); 17 | config.photosMaxCount = 9; 18 | #####**create pickerView** 19 | WSImagePickerView *pickerView = [[WSImagePickerView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0) config:config]; 20 | //Height changed with photo selection 21 | __weak typeof(self) weakSelf = self; 22 | pickerView.viewHeightChanged = ^(CGFloat height) { 23 | weakSelf.photoViewHieghtConstraint.constant = height; 24 | [weakSelf.view setNeedsLayout]; 25 | [weakSelf.view layoutIfNeeded]; 26 | }; 27 | 28 | pickerView.navigationController = self.navigationController; 29 | [self.photoView addSubview:pickerView]; 30 | self.pickerView = pickerView; 31 | 32 | //refresh superview height 33 | [pickerView refreshImagePickerViewWithPhotoArray:nil]; 34 | 35 | 36 | 37 | #####**get photos** 38 | NSArray *array = [self.pickerView getPhotos]; 39 | 40 | -------------------------------------------------------------------------------- /WSImagePicker.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /WSImagePicker.xcodeproj/project.xcworkspace/xcshareddata/WSImagePicker.xcscmblueprint: -------------------------------------------------------------------------------- 1 | { 2 | "DVTSourceControlWorkspaceBlueprintPrimaryRemoteRepositoryKey" : "65E44FAD727851099702505E736C1D8A51419335", 3 | "DVTSourceControlWorkspaceBlueprintWorkingCopyRepositoryLocationsKey" : { 4 | 5 | }, 6 | "DVTSourceControlWorkspaceBlueprintWorkingCopyStatesKey" : { 7 | "65E44FAD727851099702505E736C1D8A51419335" : 9223372036854775807, 8 | "F6DE7D672E948E559F33BFF3775DF56D2A8270C4" : 9223372036854775807 9 | }, 10 | "DVTSourceControlWorkspaceBlueprintIdentifierKey" : "DB6313A7-892D-4A6F-B01D-BF89E26063D0", 11 | "DVTSourceControlWorkspaceBlueprintWorkingCopyPathsKey" : { 12 | "65E44FAD727851099702505E736C1D8A51419335" : "WSImagePickerDemo\/", 13 | "F6DE7D672E948E559F33BFF3775DF56D2A8270C4" : "WSImagePicker\/" 14 | }, 15 | "DVTSourceControlWorkspaceBlueprintNameKey" : "WSImagePicker", 16 | "DVTSourceControlWorkspaceBlueprintVersion" : 204, 17 | "DVTSourceControlWorkspaceBlueprintRelativePathToProjectKey" : "WSImagePicker.xcodeproj", 18 | "DVTSourceControlWorkspaceBlueprintRemoteRepositoriesKey" : [ 19 | { 20 | "DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "https:\/\/github.com\/wsjtwzs\/WSImagePicker.git", 21 | "DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git", 22 | "DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "65E44FAD727851099702505E736C1D8A51419335" 23 | }, 24 | { 25 | "DVTSourceControlWorkspaceBlueprintRemoteRepositoryURLKey" : "https:\/\/github.com\/wsjtwzs\/WSImagePicker.git", 26 | "DVTSourceControlWorkspaceBlueprintRemoteRepositorySystemKey" : "com.apple.dt.Xcode.sourcecontrol.Git", 27 | "DVTSourceControlWorkspaceBlueprintRemoteRepositoryIdentifierKey" : "F6DE7D672E948E559F33BFF3775DF56D2A8270C4" 28 | } 29 | ] 30 | } -------------------------------------------------------------------------------- /WSImagePicker.xcodeproj/project.xcworkspace/xcuserdata/wsjtwzs.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wsjtwzs/WSImagePicker/a8928871444ac19d0155ba574dd3dcee13d816cc/WSImagePicker.xcodeproj/project.xcworkspace/xcuserdata/wsjtwzs.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /WSImagePicker.xcodeproj/xcuserdata/wsjtwzs.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 8 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /WSImagePicker.xcodeproj/xcuserdata/wsjtwzs.xcuserdatad/xcschemes/WSImagePicker.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 54 | 56 | 62 | 63 | 64 | 65 | 66 | 67 | 73 | 75 | 81 | 82 | 83 | 84 | 86 | 87 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /WSImagePicker.xcodeproj/xcuserdata/wsjtwzs.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | WSImagePicker.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 2E1E50EA1DB4A11A0019F18D 16 | 17 | primary 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /WSImagePicker/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wsjtwzs/WSImagePicker/a8928871444ac19d0155ba574dd3dcee13d816cc/WSImagePicker/.DS_Store -------------------------------------------------------------------------------- /WSImagePicker/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // WSImagePicker 4 | // 5 | // Created by 吴振松 on 16/10/17. 6 | // Copyright © 2016年 wsjtwzs. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /WSImagePicker/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // WSImagePicker 4 | // 5 | // Created by 吴振松 on 16/10/17. 6 | // Copyright © 2016年 wsjtwzs. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | 11 | @interface AppDelegate () 12 | 13 | @end 14 | 15 | @implementation AppDelegate 16 | 17 | 18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 19 | [UINavigationBar appearance].translucent = NO; 20 | return YES; 21 | } 22 | 23 | 24 | - (void)applicationWillResignActive:(UIApplication *)application { 25 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 26 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 27 | } 28 | 29 | 30 | - (void)applicationDidEnterBackground:(UIApplication *)application { 31 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 32 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 33 | } 34 | 35 | 36 | - (void)applicationWillEnterForeground:(UIApplication *)application { 37 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 38 | } 39 | 40 | 41 | - (void)applicationDidBecomeActive:(UIApplication *)application { 42 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 43 | } 44 | 45 | 46 | - (void)applicationWillTerminate:(UIApplication *)application { 47 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 48 | } 49 | 50 | 51 | @end 52 | -------------------------------------------------------------------------------- /WSImagePicker/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "20x20", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "20x20", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "29x29", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "29x29", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "40x40", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "40x40", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "size" : "60x60", 36 | "scale" : "2x" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "size" : "60x60", 41 | "scale" : "3x" 42 | } 43 | ], 44 | "info" : { 45 | "version" : 1, 46 | "author" : "xcode" 47 | } 48 | } -------------------------------------------------------------------------------- /WSImagePicker/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /WSImagePicker/Assets.xcassets/bg/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /WSImagePicker/Assets.xcassets/bg/bg_photo_add.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "scale" : "1x" 6 | }, 7 | { 8 | "idiom" : "universal", 9 | "filename" : "转售-添加图片.png", 10 | "scale" : "2x" 11 | }, 12 | { 13 | "idiom" : "universal", 14 | "scale" : "3x" 15 | } 16 | ], 17 | "info" : { 18 | "version" : 1, 19 | "author" : "xcode" 20 | } 21 | } -------------------------------------------------------------------------------- /WSImagePicker/Assets.xcassets/bg/bg_photo_add.imageset/转售-添加图片.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wsjtwzs/WSImagePicker/a8928871444ac19d0155ba574dd3dcee13d816cc/WSImagePicker/Assets.xcassets/bg/bg_photo_add.imageset/转售-添加图片.png -------------------------------------------------------------------------------- /WSImagePicker/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /WSImagePicker/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /WSImagePicker/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | LSRequiresIPhoneOS 22 | 23 | NSAppTransportSecurity 24 | 25 | NSAllowsArbitraryLoads 26 | 27 | 28 | NSAppleMusicUsageDescription 29 | 允许应用访问您的相册 30 | NSCameraUsageDescription 31 | 允许应用使用您的相机 32 | NSPhotoLibraryUsageDescription 33 | 允许应用访问您的相册 34 | UILaunchStoryboardName 35 | LaunchScreen 36 | UIMainStoryboardFile 37 | Main 38 | UIRequiredDeviceCapabilities 39 | 40 | armv7 41 | 42 | UISupportedInterfaceOrientations 43 | 44 | UIInterfaceOrientationPortrait 45 | UIInterfaceOrientationLandscapeLeft 46 | UIInterfaceOrientationLandscapeRight 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /WSImagePicker/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // WSImagePicker 4 | // 5 | // Created by 吴振松 on 16/10/17. 6 | // Copyright © 2016年 wsjtwzs. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /WSImagePicker/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // WSImagePicker 4 | // 5 | // Created by 吴振松 on 16/10/17. 6 | // Copyright © 2016年 wsjtwzs. All rights reserved. 7 | // 8 | 9 | // 常量定义 10 | #define kScreenWidth [[UIScreen mainScreen] bounds].size.width 11 | #define kScreenHeight [[UIScreen mainScreen] bounds].size.height 12 | 13 | #import "ViewController.h" 14 | #import "WSImagePickerView.h" 15 | @interface ViewController () 16 | @property (weak, nonatomic) IBOutlet UIView *photoView; 17 | @property (weak, nonatomic) IBOutlet NSLayoutConstraint *photoViewHieghtConstraint; 18 | @property (nonatomic, strong) WSImagePickerView *pickerView; 19 | @end 20 | 21 | @implementation ViewController 22 | 23 | - (void)viewDidLoad { 24 | [super viewDidLoad]; 25 | [self setupPickerView]; 26 | } 27 | - (void)setupPickerView { 28 | 29 | //imagePickerView parameter settings 30 | WSImagePickerConfig *config = [WSImagePickerConfig new]; 31 | config.itemSize = CGSizeMake(80, 80); 32 | config.photosMaxCount = 9; 33 | 34 | WSImagePickerView *pickerView = [[WSImagePickerView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0) config:config]; 35 | //Height changed with photo selection 36 | __weak typeof(self) weakSelf = self; 37 | pickerView.viewHeightChanged = ^(CGFloat height) { 38 | weakSelf.photoViewHieghtConstraint.constant = height; 39 | [weakSelf.view setNeedsLayout]; 40 | [weakSelf.view layoutIfNeeded]; 41 | }; 42 | pickerView.navigationController = self.navigationController; 43 | [self.photoView addSubview:pickerView]; 44 | self.pickerView = pickerView; 45 | 46 | //refresh superview height 47 | [pickerView refreshImagePickerViewWithPhotoArray:nil]; 48 | } 49 | 50 | - (IBAction)onClickConfirm:(id)sender { 51 | NSArray *array = [_pickerView getPhotos]; 52 | NSLog(@"%@",array); 53 | [[[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"共选择了%@张照片",@(array.count)] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show]; 54 | } 55 | 56 | 57 | - (void)didReceiveMemoryWarning { 58 | [super didReceiveMemoryWarning]; 59 | // Dispose of any resources that can be recreated. 60 | } 61 | 62 | 63 | @end 64 | -------------------------------------------------------------------------------- /WSImagePicker/WSImagePicker/WSImagePickerView.h: -------------------------------------------------------------------------------- 1 | // 2 | // WSImagePickerView.h 3 | // WSImagePicker 4 | // 5 | // Created by 吴振松 on 16/10/17. 6 | // Copyright © 2016年 wsjtwzs. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class WSImagePickerConfig; 12 | @interface WSImagePickerView : UIView 13 | 14 | @property (nonatomic, weak) UINavigationController *navigationController; 15 | @property (nonatomic, copy) void(^viewHeightChanged)(CGFloat height); 16 | 17 | - (instancetype)initWithFrame:(CGRect)frame config:(WSImagePickerConfig *)config; 18 | - (void)refreshImagePickerViewWithPhotoArray:(NSArray *)array; 19 | - (NSArray *)getPhotos; 20 | @end 21 | 22 | @interface WSImagePickerConfig : NSObject 23 | 24 | @property (nonatomic, assign) CGSize itemSize; //每张图片的缩略图尺寸 默认CGSizeMake(60, 60); 25 | @property (nonatomic, assign) UIEdgeInsets sectionInset; //距离上下左右的边距 默认UIEdgeInsetsMake(10, 10, 10, 10); 26 | @property (nonatomic, assign) CGFloat minimumLineSpacing; //最小行高 默认10.0f; 27 | @property (nonatomic, assign) CGFloat minimumInteritemSpacing; //最小列宽 默认10.0f; 28 | @property (nonatomic, assign) NSInteger photosMaxCount; //最多选择照片张数 默认9张 29 | 30 | @end 31 | -------------------------------------------------------------------------------- /WSImagePicker/WSImagePicker/WSImagePickerView.m: -------------------------------------------------------------------------------- 1 | // 2 | // WSImagePickerView.m 3 | // WSImagePicker 4 | // 5 | // Created by 吴振松 on 16/10/17. 6 | // Copyright © 2016年 wsjtwzs. All rights reserved. 7 | // 8 | 9 | #import "WSImagePickerView.h" 10 | #import "WSPhotosBroseVC.h" 11 | #import "JFImagePickerController.h" 12 | 13 | static NSString *imagePickerCellIdentifier = @"imagePickerCellIdentifier"; 14 | 15 | @interface WSImagePickerView() 16 | { 17 | NSMutableArray *_photosArray; 18 | } 19 | @property (nonatomic, strong) UICollectionView *collectionView; 20 | @property (nonatomic, strong) WSImagePickerConfig *config; 21 | @end 22 | 23 | @implementation WSImagePickerView 24 | 25 | - (instancetype)initWithFrame:(CGRect)frame config:(WSImagePickerConfig *)config{ 26 | if(self = [super initWithFrame:frame]) { 27 | _config = (config != nil)?config:([WSImagePickerConfig new]); 28 | [self setupView]; 29 | [self initializeData]; 30 | } 31 | return self; 32 | } 33 | 34 | - (instancetype)initWithFrame:(CGRect)frame { 35 | return [self initWithFrame:frame config:nil]; 36 | } 37 | 38 | - (void)setupView { 39 | self.backgroundColor = [UIColor clearColor]; 40 | 41 | UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new]; 42 | layout.itemSize = _config.itemSize; 43 | layout.sectionInset = _config.sectionInset; 44 | layout.minimumLineSpacing = _config.minimumLineSpacing; 45 | layout.minimumInteritemSpacing = _config.minimumInteritemSpacing; 46 | 47 | _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout]; 48 | _collectionView.delegate = self; 49 | _collectionView.dataSource = self; 50 | _collectionView.clipsToBounds = YES; 51 | _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 52 | _collectionView.showsVerticalScrollIndicator = NO; 53 | _collectionView.showsHorizontalScrollIndicator = NO; 54 | _collectionView.bounces = NO; 55 | _collectionView.backgroundColor = [UIColor clearColor]; 56 | [self addSubview:_collectionView]; 57 | [_collectionView reloadData]; 58 | 59 | [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:imagePickerCellIdentifier]; 60 | } 61 | 62 | - (void)initializeData { 63 | _photosArray = [NSMutableArray new]; 64 | } 65 | 66 | - (void)refreshCollectionView { 67 | NSInteger n; 68 | CGFloat width = _collectionView.frame.size.width - _config.sectionInset.left - _config.sectionInset.right; 69 | n = (width + _config.minimumInteritemSpacing)/(_config.itemSize.width + _config.minimumInteritemSpacing); 70 | CGFloat height = ((NSInteger)(_photosArray.count)/n +1) * (_config.itemSize.height + _config.minimumLineSpacing); 71 | height -= _config.minimumLineSpacing; 72 | height += _config.sectionInset.top; 73 | height += _config.sectionInset.bottom; 74 | CGRect frame = self.frame; 75 | frame.size.height = height; 76 | self.frame = frame; 77 | [_collectionView reloadData]; 78 | if(self.viewHeightChanged) { 79 | self.viewHeightChanged(height); 80 | } 81 | } 82 | 83 | - (void)refreshImagePickerViewWithPhotoArray:(NSArray *)array { 84 | if(array.count > 0) { 85 | [_photosArray removeAllObjects]; 86 | [_photosArray addObjectsFromArray:array]; 87 | } 88 | [self refreshCollectionView]; 89 | } 90 | 91 | - (NSArray *)getPhotos { 92 | NSArray *array = [NSArray arrayWithArray:_photosArray]; 93 | return array; 94 | } 95 | 96 | #pragma make - collectionViewDelegate - 97 | 98 | - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ 99 | if(_photosArray.count < _config.photosMaxCount) { 100 | return _photosArray.count + 1; 101 | } 102 | return _photosArray.count; 103 | } 104 | 105 | - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 106 | UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:imagePickerCellIdentifier forIndexPath:indexPath]; 107 | UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:1]; 108 | if (!imgView) { 109 | imgView = [[UIImageView alloc] initWithFrame:cell.bounds]; 110 | imgView.contentMode = UIViewContentModeScaleAspectFill; 111 | imgView.clipsToBounds = YES; 112 | imgView.tag = 1; 113 | [cell addSubview:imgView]; 114 | } 115 | if(indexPath.row < _photosArray.count) { 116 | UIImage *image = _photosArray[indexPath.row]; 117 | imgView.image = image; 118 | } 119 | else { 120 | imgView.image = nil; 121 | imgView.image = [UIImage imageNamed:@"bg_photo_add"]; 122 | } 123 | return cell; 124 | } 125 | 126 | - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 127 | { 128 | NSMutableArray *tmpArray = [NSMutableArray new]; 129 | if(indexPath.row < _photosArray.count) { 130 | for (UIImage *image in _photosArray) { 131 | WSImageModel *model = [WSImageModel new]; 132 | model.image = image; 133 | [tmpArray addObject:model]; 134 | } 135 | 136 | WSPhotosBroseVC *vc = [WSPhotosBroseVC new]; 137 | vc.imageArray = tmpArray; 138 | vc.showIndex = indexPath.row; 139 | vc.completion = ^ (NSArray *array){ 140 | dispatch_async(dispatch_get_main_queue(), ^{ 141 | [_photosArray removeAllObjects]; 142 | [_photosArray addObjectsFromArray:array]; 143 | [self refreshCollectionView]; 144 | }); 145 | }; 146 | [self.navigationController pushViewController:vc animated:YES]; 147 | } 148 | else { 149 | [self pickPhotos]; 150 | } 151 | } 152 | 153 | - (void)pickPhotos{ 154 | UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从照片库选取",nil]; 155 | [action showInView:self.navigationController.view]; 156 | } 157 | 158 | 159 | #pragma mark - UIActionSheet delegate - 160 | - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { 161 | switch (buttonIndex) { 162 | case 0: 163 | { 164 | UIImagePickerController *vc = [UIImagePickerController new]; 165 | vc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera,photoLibrary和photoAlbum 166 | vc.delegate = self; 167 | [self.navigationController presentViewController:vc animated:YES completion:nil]; 168 | } 169 | break; 170 | case 1: 171 | { 172 | NSInteger count = _config.photosMaxCount - _photosArray.count; 173 | [JFImagePickerController setMaxCount:count]; 174 | JFImagePickerController *picker = [[JFImagePickerController alloc] initWithRootViewController:[UIViewController new]]; 175 | picker.pickerDelegate = self; 176 | [self.navigationController presentViewController:picker animated:YES completion:nil]; 177 | } 178 | break; 179 | 180 | default: 181 | break; 182 | } 183 | } 184 | 185 | 186 | #pragma mark - JFImagePicker Delegate - 187 | 188 | - (void)imagePickerDidFinished:(JFImagePickerController *)picker{ 189 | 190 | __weak typeof(self) weakself = self; 191 | for (ALAsset *asset in picker.assets) { 192 | [[JFImageManager sharedManager] imageWithAsset:asset resultHandler:^(CGImageRef imageRef, BOOL longImage) { 193 | UIImage *image = [UIImage imageWithCGImage:imageRef]; 194 | dispatch_async(dispatch_get_main_queue(), ^{ 195 | [_photosArray addObject:image]; 196 | [weakself refreshCollectionView]; 197 | }); 198 | }]; 199 | } 200 | [self imagePickerDidCancel:picker]; 201 | } 202 | 203 | - (void)imagePickerDidCancel:(JFImagePickerController *)picker{ 204 | [picker dismissViewControllerAnimated:YES completion:nil]; 205 | [JFImagePickerController clear]; 206 | } 207 | 208 | #pragma mark - imagePickerController Delegate - 209 | - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 210 | { 211 | [self imageHandleWithpickerController:picker MdediaInfo:info]; 212 | } 213 | 214 | - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { 215 | [picker dismissViewControllerAnimated:YES completion:^{}]; 216 | } 217 | 218 | - (void)imageHandleWithpickerController:(UIImagePickerController *)picker MdediaInfo:(NSDictionary *)info { 219 | 220 | UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; 221 | [_photosArray addObject:image]; 222 | [self refreshCollectionView]; 223 | [picker dismissViewControllerAnimated:YES completion:^{}]; 224 | } 225 | 226 | 227 | @end 228 | 229 | @implementation WSImagePickerConfig 230 | 231 | - (instancetype)init { 232 | if(self = [super init]) { 233 | _itemSize = CGSizeMake(60, 60); 234 | _sectionInset = UIEdgeInsetsMake(10, 10, 10, 10); 235 | _minimumLineSpacing = 10.0f; 236 | _minimumInteritemSpacing = 10.0f; 237 | _photosMaxCount = 9; 238 | } 239 | return self; 240 | } 241 | 242 | 243 | @end 244 | -------------------------------------------------------------------------------- /WSImagePicker/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // WSImagePicker 4 | // 5 | // Created by 吴振松 on 16/10/17. 6 | // Copyright © 2016年 wsjtwzs. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | --------------------------------------------------------------------------------