├── README.md ├── 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 ├── UIImage+WebP.h ├── UIImage+WebP.m ├── UIImageView+HighlightedWebCache.h ├── UIImageView+HighlightedWebCache.m ├── UIImageView+WebCache.h ├── UIImageView+WebCache.m ├── UIView+WebCacheOperation.h └── UIView+WebCacheOperation.m ├── shufflingDemo.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── yangxin.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ └── yangxin.xcuserdatad │ ├── xcdebugger │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ ├── shufflingDemo.xcscheme │ └── xcschememanagement.plist ├── shufflingDemo ├── AppDelegate.h ├── AppDelegate.m ├── Assets.xcassets │ └── AppIcon.appiconset │ │ └── Contents.json ├── Base.lproj │ ├── LaunchScreen.storyboard │ └── Main.storyboard ├── Info.plist ├── MKShufflingView.h ├── MKShufflingView.m ├── MKpageStyle.h ├── MKpageStyle.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 │ ├── UIImage+WebP.h │ ├── UIImage+WebP.m │ ├── UIImageView+HighlightedWebCache.h │ ├── UIImageView+HighlightedWebCache.m │ ├── UIImageView+WebCache.h │ ├── UIImageView+WebCache.m │ ├── UIView+WebCacheOperation.h │ └── UIView+WebCacheOperation.m ├── ViewController.h ├── ViewController.m ├── favorites-filling-2.png ├── favorites-filling.png ├── main.m └── 演示.gif └── shufflingDemoTests ├── Info.plist └── shufflingDemoTests.m /README.md: -------------------------------------------------------------------------------- 1 | # SlidingPositive 2 | 一个强大的轮播实现。 3 | 4 | 5 | 6 | ![image](https://github.com/yangxiniOS/SlidingPositive/blob/master/shufflingDemo/演示.gif) 7 | 8 | 9 | 10 | 支持图片轮播,文字轮播,正反序,水平竖直方向只需要赋值调用即可,即可实现无限轮播 11 | 12 | 应广大使用者需求现添加如下功能 13 | 14 | 新增网络图片 15 | 高度自定义PageControl 支持数字显示,图片显示,可以设置在轮播的任何位置,可以设置任何图片,点击切换等等,随君设置 16 | 如何调用 17 | 18 | self.shufflingView = [[MKShufflingView alloc]initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 250)]; 19 | [self.view addSubview:self.shufflingView]; 20 | self.shufflingView.backgroundColor = [UIColor redColor]; 21 | self.shufflingView.textArray =@[@"http://f.hiphotos.baidu.com/zhidao/pic/item/810a19d8bc3eb1357689ea10a71ea8d3fc1f44ca.jpg",@"http://imgsrc.baidu.com/forum/w%3D580/sign=fcae01763b87e9504217f3642039531b/2f2eb9389b504fc29fccbeb0e4dde71191ef6df7.jpg",@"http://d.hiphotos.baidu.com/zhidao/pic/item/4ec2d5628535e5dd5c955af875c6a7efce1b6258.jpg",@"http://c.hiphotos.baidu.com/zhidao/pic/item/95eef01f3a292df59ac3846ebc315c6034a8734c.jpg",@"http://img.hb.aicdn.com/c6c4f5ebe51328518bdcad6dfe3ee6530ff75e1d132be-FPDHXd_fw580"]; 22 | self.shufflingView.MYshufflingViewShowstyle = shufflingViewShowstyleImageView; 23 | self.shufflingView.isUrlImage = YES; 24 | self.shufflingView.selected = 3; 25 | self.shufflingView.isAutomatic = YES; 26 | self.shufflingView.isShowMyPage = YES; 27 | MKpageStyle *myStytle = [[MKpageStyle alloc]init]; 28 | myStytle.myPageStyle = MKpageStyleLocationBottom; 29 | myStytle.pageHeight = 30; 30 | myStytle.myDotStyle = MKDotStyleLocationCenter; 31 | myStytle.backGroundColor = [UIColor clearColor]; 32 | myStytle.styleTextColor = [UIColor whiteColor]; 33 | myStytle.currentTextColor = [UIColor greenColor]; 34 | myStytle.myDotFillStyle = MKDotStyleText; 35 | self.shufflingView.mypageStyle = myStytle; 36 | self.shufflingView.MYslidingDirection = slidingDirectionH; 37 | self.shufflingView.MYslidingPositiveOrNegative = slidingPositive; 38 | [self.shufflingView initShufflingView:^(NSInteger selected) { 39 | NSLog(@"%ld",selected); 40 | }]; 41 | 42 | 技术交流解惑QQ群426981364 43 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. 41 | */ 42 | @property (assign, nonatomic) NSUInteger maxMemoryCost; 43 | 44 | /** 45 | * The maximum length of time to keep an image in the cache, in seconds 46 | */ 47 | @property (assign, nonatomic) NSInteger maxCacheAge; 48 | 49 | /** 50 | * The maximum size of the cache, in bytes. 51 | */ 52 | @property (assign, nonatomic) NSUInteger maxCacheSize; 53 | 54 | /** 55 | * Returns global shared cache instance 56 | * 57 | * @return SDImageCache global instance 58 | */ 59 | + (SDImageCache *)sharedImageCache; 60 | 61 | /** 62 | * Init a new cache store with a specific namespace 63 | * 64 | * @param ns The namespace to use for this cache store 65 | */ 66 | - (id)initWithNamespace:(NSString *)ns; 67 | 68 | /** 69 | * Add a read-only cache path to search for images pre-cached by SDImageCache 70 | * Useful if you want to bundle pre-loaded images with your app 71 | * 72 | * @param path The path to use for this read-only cache path 73 | */ 74 | - (void)addReadOnlyCachePath:(NSString *)path; 75 | 76 | /** 77 | * Store an image into memory and disk cache at the given key. 78 | * 79 | * @param image The image to store 80 | * @param key The unique image cache key, usually it's image absolute URL 81 | */ 82 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key; 83 | 84 | /** 85 | * Store an image into memory and optionally disk cache at the given key. 86 | * 87 | * @param image The image to store 88 | * @param key The unique image cache key, usually it's image absolute URL 89 | * @param toDisk Store the image to disk cache if YES 90 | */ 91 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; 92 | 93 | /** 94 | * Store an image into memory and optionally disk cache at the given key. 95 | * 96 | * @param image The image to store 97 | * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage 98 | * @param imageData The image data as returned by the server, this representation will be used for disk storage 99 | * instead of converting the given image object into a storable/compressed image format in order 100 | * to save quality and CPU 101 | * @param key The unique image cache key, usually it's image absolute URL 102 | * @param toDisk Store the image to disk cache if YES 103 | */ 104 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; 105 | 106 | /** 107 | * Query the disk cache asynchronously. 108 | * 109 | * @param key The unique key used to store the wanted image 110 | */ 111 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; 112 | 113 | /** 114 | * Query the memory cache synchronously. 115 | * 116 | * @param key The unique key used to store the wanted image 117 | */ 118 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; 119 | 120 | /** 121 | * Query the disk cache synchronously after checking the memory cache. 122 | * 123 | * @param key The unique key used to store the wanted image 124 | */ 125 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key; 126 | 127 | /** 128 | * Remove the image from memory and disk cache synchronously 129 | * 130 | * @param key The unique image cache key 131 | */ 132 | - (void)removeImageForKey:(NSString *)key; 133 | 134 | 135 | /** 136 | * Remove the image from memory and disk cache synchronously 137 | * 138 | * @param key The unique image cache key 139 | * @param completion An block that should be executed after the image has been removed (optional) 140 | */ 141 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion; 142 | 143 | /** 144 | * Remove the image from memory and optionally disk cache synchronously 145 | * 146 | * @param key The unique image cache key 147 | * @param fromDisk Also remove cache entry from disk if YES 148 | */ 149 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; 150 | 151 | /** 152 | * Remove the image from memory and optionally disk cache synchronously 153 | * 154 | * @param key The unique image cache key 155 | * @param fromDisk Also remove cache entry from disk if YES 156 | * @param completion An block that should be executed after the image has been removed (optional) 157 | */ 158 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion; 159 | 160 | /** 161 | * Clear all memory cached images 162 | */ 163 | - (void)clearMemory; 164 | 165 | /** 166 | * Clear all disk cached images. Non-blocking method - returns immediately. 167 | * @param completion An block that should be executed after cache expiration completes (optional) 168 | */ 169 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion; 170 | 171 | /** 172 | * Clear all disk cached images 173 | * @see clearDiskOnCompletion: 174 | */ 175 | - (void)clearDisk; 176 | 177 | /** 178 | * Remove all expired cached image from disk. Non-blocking method - returns immediately. 179 | * @param completionBlock An block that should be executed after cache expiration completes (optional) 180 | */ 181 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock; 182 | 183 | /** 184 | * Remove all expired cached image from disk 185 | * @see cleanDiskWithCompletionBlock: 186 | */ 187 | - (void)cleanDisk; 188 | 189 | /** 190 | * Get the size used by the disk cache 191 | */ 192 | - (NSUInteger)getSize; 193 | 194 | /** 195 | * Get the number of images in the disk cache 196 | */ 197 | - (NSUInteger)getDiskCount; 198 | 199 | /** 200 | * Asynchronously calculate the disk cache's size. 201 | */ 202 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock; 203 | 204 | /** 205 | * Async check if image exists in disk cache already (does not load the image) 206 | * 207 | * @param key the key describing the url 208 | * @param completionBlock the block to be executed when the check is done. 209 | * @note the completion block will be always executed on the main queue 210 | */ 211 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 212 | 213 | /** 214 | * Check if image exists in disk cache already (does not load the image) 215 | * 216 | * @param key the key describing the url 217 | * 218 | * @return YES if an image exists for the given key 219 | */ 220 | - (BOOL)diskImageExistsWithKey:(NSString *)key; 221 | 222 | /** 223 | * Get the cache path for a certain key (needs the cache path root folder) 224 | * 225 | * @param key the key (can be obtained from url using cacheKeyForURL) 226 | * @param path the cach path root folder 227 | * 228 | * @return the cache path 229 | */ 230 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path; 231 | 232 | /** 233 | * Get the default cache path for a certain key 234 | * 235 | * @param key the key (can be obtained from url using cacheKeyForURL) 236 | * 237 | * @return the default cache path 238 | */ 239 | - (NSString *)defaultCachePathForKey:(NSString *)key; 240 | 241 | @end 242 | -------------------------------------------------------------------------------- /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 < __IPHONE_5_0 17 | #error SDWebImage doesn't support Deployement 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 | #define dispatch_main_sync_safe(block)\ 59 | if ([NSThread isMainThread]) {\ 60 | block();\ 61 | } else {\ 62 | dispatch_sync(dispatch_get_main_queue(), block);\ 63 | } 64 | 65 | #define dispatch_main_async_safe(block)\ 66 | if ([NSThread isMainThread]) {\ 67 | block();\ 68 | } else {\ 69 | dispatch_async(dispatch_get_main_queue(), block);\ 70 | } 71 | -------------------------------------------------------------------------------- /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.0; 32 | if (key.length >= 8) { 33 | // Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext) 34 | NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)]; 35 | if (range.location != NSNotFound) { 36 | scale = 2.0; 37 | } 38 | } 39 | 40 | UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; 41 | image = scaledImage; 42 | } 43 | return image; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | if (image.images) { 17 | // Do not decode animated images 18 | return image; 19 | } 20 | 21 | CGImageRef imageRef = image.CGImage; 22 | CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); 23 | CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; 24 | 25 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 26 | CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); 27 | 28 | int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask); 29 | BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone || 30 | infoMask == kCGImageAlphaNoneSkipFirst || 31 | infoMask == kCGImageAlphaNoneSkipLast); 32 | 33 | // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. 34 | // https://developer.apple.com/library/mac/#qa/qa1037/_index.html 35 | if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) { 36 | // Unset the old alpha info. 37 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 38 | 39 | // Set noneSkipFirst. 40 | bitmapInfo |= kCGImageAlphaNoneSkipFirst; 41 | } 42 | // Some PNGs tell us they have alpha but only 3 components. Odd. 43 | else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { 44 | // Unset the old alpha info. 45 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 46 | bitmapInfo |= kCGImageAlphaPremultipliedFirst; 47 | } 48 | 49 | // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. 50 | CGContextRef context = CGBitmapContextCreate(NULL, 51 | imageSize.width, 52 | imageSize.height, 53 | CGImageGetBitsPerComponent(imageRef), 54 | 0, 55 | colorSpace, 56 | bitmapInfo); 57 | CGColorSpaceRelease(colorSpace); 58 | 59 | // If failed, return undecompressed image 60 | if (!context) return image; 61 | 62 | CGContextDrawImage(context, imageRect, imageRef); 63 | CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); 64 | 65 | CGContextRelease(context); 66 | 67 | UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation]; 68 | CGImageRelease(decompressedImageRef); 69 | return decompressedImage; 70 | } 71 | 72 | @end 73 | -------------------------------------------------------------------------------- /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 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 ceriticates. 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 | }; 55 | 56 | typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { 57 | /** 58 | * Default value. All download operations will execute in queue style (first-in-first-out). 59 | */ 60 | SDWebImageDownloaderFIFOExecutionOrder, 61 | 62 | /** 63 | * All download operations will execute in stack style (last-in-first-out). 64 | */ 65 | SDWebImageDownloaderLIFOExecutionOrder 66 | }; 67 | 68 | extern NSString *const SDWebImageDownloadStartNotification; 69 | extern NSString *const SDWebImageDownloadStopNotification; 70 | 71 | typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); 72 | 73 | typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); 74 | 75 | typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers); 76 | 77 | /** 78 | * Asynchronous downloader dedicated and optimized for image loading. 79 | */ 80 | @interface SDWebImageDownloader : NSObject 81 | 82 | @property (assign, nonatomic) NSInteger maxConcurrentDownloads; 83 | 84 | /** 85 | * Shows the current amount of downloads that still need to be downloaded 86 | */ 87 | 88 | @property (readonly, nonatomic) NSUInteger currentDownloadCount; 89 | 90 | 91 | /** 92 | * The timeout value (in seconds) for the download operation. Default: 15.0. 93 | */ 94 | @property (assign, nonatomic) NSTimeInterval downloadTimeout; 95 | 96 | 97 | /** 98 | * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. 99 | */ 100 | @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; 101 | 102 | /** 103 | * Singleton method, returns the shared instance 104 | * 105 | * @return global shared instance of downloader class 106 | */ 107 | + (SDWebImageDownloader *)sharedDownloader; 108 | 109 | /** 110 | * Set username 111 | */ 112 | @property (strong, nonatomic) NSString *username; 113 | 114 | /** 115 | * Set password 116 | */ 117 | @property (strong, nonatomic) NSString *password; 118 | 119 | /** 120 | * Set filter to pick headers for downloading image HTTP request. 121 | * 122 | * This block will be invoked for each downloading image request, returned 123 | * NSDictionary will be used as headers in corresponding HTTP request. 124 | */ 125 | @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter; 126 | 127 | /** 128 | * Set a value for a HTTP header to be appended to each download HTTP request. 129 | * 130 | * @param value The value for the header field. Use `nil` value to remove the header. 131 | * @param field The name of the header field to set. 132 | */ 133 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; 134 | 135 | /** 136 | * Returns the value of the specified HTTP header field. 137 | * 138 | * @return The value associated with the header field field, or `nil` if there is no corresponding header field. 139 | */ 140 | - (NSString *)valueForHTTPHeaderField:(NSString *)field; 141 | 142 | /** 143 | * Sets a subclass of `SDWebImageDownloaderOperation` as the default 144 | * `NSOperation` to be used each time SDWebImage constructs a request 145 | * operation to download an image. 146 | * 147 | * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set 148 | * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. 149 | */ 150 | - (void)setOperationClass:(Class)operationClass; 151 | 152 | /** 153 | * Creates a SDWebImageDownloader async downloader instance with a given URL 154 | * 155 | * The delegate will be informed when the image is finish downloaded or an error has happen. 156 | * 157 | * @see SDWebImageDownloaderDelegate 158 | * 159 | * @param url The URL to the image to download 160 | * @param options The options to be used for this download 161 | * @param progressBlock A block called repeatedly while the image is downloading 162 | * @param completedBlock A block called once the download is completed. 163 | * If the download succeeded, the image parameter is set, in case of error, 164 | * error parameter is set with the error. The last parameter is always YES 165 | * if SDWebImageDownloaderProgressiveDownload isn't use. With the 166 | * SDWebImageDownloaderProgressiveDownload option, this block is called 167 | * repeatedly with the partial image object and the finished argument set to NO 168 | * before to be called a last time with the full image and finished argument 169 | * set to YES. In case of error, the finished argument is always YES. 170 | * 171 | * @return A cancellable SDWebImageOperation 172 | */ 173 | - (id )downloadImageWithURL:(NSURL *)url 174 | options:(SDWebImageDownloaderOptions)options 175 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 176 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock; 177 | 178 | /** 179 | * Sets the download queue suspension state 180 | */ 181 | - (void)setSuspended:(BOOL)suspended; 182 | 183 | @end 184 | -------------------------------------------------------------------------------- /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 | @interface SDWebImageDownloaderOperation : NSOperation 14 | 15 | /** 16 | * The request used by the operation's connection. 17 | */ 18 | @property (strong, nonatomic, readonly) NSURLRequest *request; 19 | 20 | /** 21 | * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. 22 | * 23 | * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. 24 | */ 25 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage; 26 | 27 | /** 28 | * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. 29 | * 30 | * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. 31 | */ 32 | @property (nonatomic, strong) NSURLCredential *credential; 33 | 34 | /** 35 | * The SDWebImageDownloaderOptions for the receiver. 36 | */ 37 | @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; 38 | 39 | /** 40 | * Initializes a `SDWebImageDownloaderOperation` object 41 | * 42 | * @see SDWebImageDownloaderOperation 43 | * 44 | * @param request the URL request 45 | * @param options downloader options 46 | * @param progressBlock the block executed when a new chunk of data arrives. 47 | * @note the progress block is executed on a background queue 48 | * @param completedBlock the block executed when the download is done. 49 | * @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 50 | * @param cancelBlock the block executed if the download (operation) is cancelled 51 | * 52 | * @return the initialized instance 53 | */ 54 | - (id)initWithRequest:(NSURLRequest *)request 55 | options:(SDWebImageDownloaderOptions)options 56 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 57 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock 58 | cancelled:(SDWebImageNoParamsBlock)cancelBlock; 59 | 60 | @end 61 | -------------------------------------------------------------------------------- /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 embeded 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 ceriticates. 62 | * Useful for testing purposes. Use with caution in production. 63 | */ 64 | SDWebImageAllowInvalidSSLCertificates = 1 << 7, 65 | 66 | /** 67 | * By default, image are loaded in the order they were queued. This flag move them to 68 | * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which 69 | * could take a while). 70 | */ 71 | SDWebImageHighPriority = 1 << 8, 72 | 73 | /** 74 | * By default, placeholder images are loaded while the image is loading. This flag will delay the loading 75 | * of the placeholder image until after the image has finished loading. 76 | */ 77 | SDWebImageDelayPlaceholder = 1 << 9, 78 | 79 | /** 80 | * We usually don't call transformDownloadedImage delegate method on animated images, 81 | * as most transformation code would mangle it. 82 | * Use this flag to transform them anyway. 83 | */ 84 | SDWebImageTransformAnimatedImage = 1 << 10, 85 | }; 86 | 87 | typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL); 88 | 89 | typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL); 90 | 91 | typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url); 92 | 93 | 94 | @class SDWebImageManager; 95 | 96 | @protocol SDWebImageManagerDelegate 97 | 98 | @optional 99 | 100 | /** 101 | * Controls which image should be downloaded when the image is not found in the cache. 102 | * 103 | * @param imageManager The current `SDWebImageManager` 104 | * @param imageURL The url of the image to be downloaded 105 | * 106 | * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. 107 | */ 108 | - (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; 109 | 110 | /** 111 | * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. 112 | * NOTE: This method is called from a global queue in order to not to block the main thread. 113 | * 114 | * @param imageManager The current `SDWebImageManager` 115 | * @param image The image to transform 116 | * @param imageURL The url of the image to transform 117 | * 118 | * @return The transformed image object. 119 | */ 120 | - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; 121 | 122 | @end 123 | 124 | /** 125 | * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. 126 | * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). 127 | * You can use this class directly to benefit from web image downloading with caching in another context than 128 | * a UIView. 129 | * 130 | * Here is a simple example of how to use SDWebImageManager: 131 | * 132 | * @code 133 | 134 | SDWebImageManager *manager = [SDWebImageManager sharedManager]; 135 | [manager downloadWithURL:imageURL 136 | options:0 137 | progress:nil 138 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 139 | if (image) { 140 | // do something with image 141 | } 142 | }]; 143 | 144 | * @endcode 145 | */ 146 | @interface SDWebImageManager : NSObject 147 | 148 | @property (weak, nonatomic) id delegate; 149 | 150 | @property (strong, nonatomic, readonly) SDImageCache *imageCache; 151 | @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; 152 | 153 | /** 154 | * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can 155 | * be used to remove dynamic part of an image URL. 156 | * 157 | * The following example sets a filter in the application delegate that will remove any query-string from the 158 | * URL before to use it as a cache key: 159 | * 160 | * @code 161 | 162 | [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { 163 | url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; 164 | return [url absoluteString]; 165 | }]; 166 | 167 | * @endcode 168 | */ 169 | @property (nonatomic, copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter; 170 | 171 | /** 172 | * Returns global SDWebImageManager instance. 173 | * 174 | * @return SDWebImageManager shared instance 175 | */ 176 | + (SDWebImageManager *)sharedManager; 177 | 178 | /** 179 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 180 | * 181 | * @param url The URL to the image 182 | * @param options A mask to specify options to use for this request 183 | * @param progressBlock A block called while image is downloading 184 | * @param completedBlock A block called when operation has been completed. 185 | * 186 | * This parameter is required. 187 | * 188 | * This block has no return value and takes the requested UIImage as first parameter. 189 | * In case of error the image parameter is nil and the second parameter may contain an NSError. 190 | * 191 | * The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache 192 | * or from the memory cache or from the network. 193 | * 194 | * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is 195 | * downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the 196 | * block is called a last time with the full image and the last parameter set to YES. 197 | * 198 | * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation 199 | */ 200 | - (id )downloadImageWithURL:(NSURL *)url 201 | options:(SDWebImageOptions)options 202 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 203 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock; 204 | 205 | /** 206 | * Saves image to cache for given URL 207 | * 208 | * @param image The image to cache 209 | * @param url The URL to the image 210 | * 211 | */ 212 | 213 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url; 214 | 215 | /** 216 | * Cancel all current opreations 217 | */ 218 | - (void)cancelAll; 219 | 220 | /** 221 | * Check one or more operations running 222 | */ 223 | - (BOOL)isRunning; 224 | 225 | /** 226 | * Check if image has already been cached 227 | * 228 | * @param url image url 229 | * 230 | * @return if the image was already cached 231 | */ 232 | - (BOOL)cachedImageExistsForURL:(NSURL *)url; 233 | 234 | /** 235 | * Check if image has already been cached on disk only 236 | * 237 | * @param url image url 238 | * 239 | * @return if the image was already cached (disk only) 240 | */ 241 | - (BOOL)diskImageExistsForURL:(NSURL *)url; 242 | 243 | /** 244 | * Async check if image has already been cached 245 | * 246 | * @param url image url 247 | * @param completionBlock the block to be executed when the check is finished 248 | * 249 | * @note the completion block is always executed on the main queue 250 | */ 251 | - (void)cachedImageExistsForURL:(NSURL *)url 252 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 253 | 254 | /** 255 | * Async check if image has already been cached on disk only 256 | * 257 | * @param url image url 258 | * @param completionBlock the block to be executed when the check is finished 259 | * 260 | * @note the completion block is always executed on the main queue 261 | */ 262 | - (void)diskImageExistsForURL:(NSURL *)url 263 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 264 | 265 | 266 | /** 267 | *Return the cache key for a given URL 268 | */ 269 | - (NSString *)cacheKeyForURL:(NSURL *)url; 270 | 271 | @end 272 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | @property (weak, nonatomic) id delegate; 62 | 63 | /** 64 | * Return the global image prefetcher instance. 65 | */ 66 | + (SDWebImagePrefetcher *)sharedImagePrefetcher; 67 | 68 | /** 69 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 70 | * currently one image is downloaded at a time, 71 | * and skips images for failed downloads and proceed to the next image in the list 72 | * 73 | * @param urls list of URLs to prefetch 74 | */ 75 | - (void)prefetchURLs:(NSArray *)urls; 76 | 77 | /** 78 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 79 | * currently one image is downloaded at a time, 80 | * and skips images for failed downloads and proceed to the next image in the list 81 | * 82 | * @param urls list of URLs to prefetch 83 | * @param progressBlock block to be called when progress updates; 84 | * first parameter is the number of completed (successful or not) requests, 85 | * second parameter is the total number of images originally requested to be prefetched 86 | * @param completionBlock block to be called when prefetching is completed 87 | * first param is the number of completed (successful or not) requests, 88 | * second parameter is the number of skipped requests 89 | */ 90 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock; 91 | 92 | /** 93 | * Remove and cancel queued list 94 | */ 95 | - (void)cancelPrefetching; 96 | 97 | 98 | @end 99 | -------------------------------------------------------------------------------- /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 | #if (!defined(DEBUG) && !defined (SD_VERBOSE)) || defined(SD_LOG_NONE) 12 | #define NSLog(...) 13 | #endif 14 | 15 | @interface SDWebImagePrefetcher () 16 | 17 | @property (strong, nonatomic) SDWebImageManager *manager; 18 | @property (strong, nonatomic) NSArray *prefetchURLs; 19 | @property (assign, nonatomic) NSUInteger requestedCount; 20 | @property (assign, nonatomic) NSUInteger skippedCount; 21 | @property (assign, nonatomic) NSUInteger finishedCount; 22 | @property (assign, nonatomic) NSTimeInterval startedTime; 23 | @property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock; 24 | @property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock; 25 | 26 | @end 27 | 28 | @implementation SDWebImagePrefetcher 29 | 30 | + (SDWebImagePrefetcher *)sharedImagePrefetcher { 31 | static dispatch_once_t once; 32 | static id instance; 33 | dispatch_once(&once, ^{ 34 | instance = [self new]; 35 | }); 36 | return instance; 37 | } 38 | 39 | - (id)init { 40 | if ((self = [super init])) { 41 | _manager = [SDWebImageManager new]; 42 | _options = SDWebImageLowPriority; 43 | self.maxConcurrentDownloads = 3; 44 | } 45 | return self; 46 | } 47 | 48 | - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { 49 | self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; 50 | } 51 | 52 | - (NSUInteger)maxConcurrentDownloads { 53 | return self.manager.imageDownloader.maxConcurrentDownloads; 54 | } 55 | 56 | - (void)startPrefetchingAtIndex:(NSUInteger)index { 57 | if (index >= self.prefetchURLs.count) return; 58 | self.requestedCount++; 59 | [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 60 | if (!finished) return; 61 | self.finishedCount++; 62 | 63 | if (image) { 64 | if (self.progressBlock) { 65 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 66 | } 67 | NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count)); 68 | } 69 | else { 70 | if (self.progressBlock) { 71 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 72 | } 73 | NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count)); 74 | 75 | // Add last failed 76 | self.skippedCount++; 77 | } 78 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { 79 | [self.delegate imagePrefetcher:self 80 | didPrefetchURL:self.prefetchURLs[index] 81 | finishedCount:self.finishedCount 82 | totalCount:self.prefetchURLs.count 83 | ]; 84 | } 85 | 86 | if (self.prefetchURLs.count > self.requestedCount) { 87 | dispatch_async(dispatch_get_main_queue(), ^{ 88 | [self startPrefetchingAtIndex:self.requestedCount]; 89 | }); 90 | } 91 | else if (self.finishedCount == self.requestedCount) { 92 | [self reportStatus]; 93 | if (self.completionBlock) { 94 | self.completionBlock(self.finishedCount, self.skippedCount); 95 | self.completionBlock = nil; 96 | } 97 | } 98 | }]; 99 | } 100 | 101 | - (void)reportStatus { 102 | NSUInteger total = [self.prefetchURLs count]; 103 | NSLog(@"Finished prefetching (%@ successful, %@ skipped, timeElasped %.2f)", @(total - self.skippedCount), @(self.skippedCount), CFAbsoluteTimeGetCurrent() - self.startedTime); 104 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { 105 | [self.delegate imagePrefetcher:self 106 | didFinishWithTotalCount:(total - self.skippedCount) 107 | skippedCount:self.skippedCount 108 | ]; 109 | } 110 | } 111 | 112 | - (void)prefetchURLs:(NSArray *)urls { 113 | [self prefetchURLs:urls progress:nil completed:nil]; 114 | } 115 | 116 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock { 117 | [self cancelPrefetching]; // Prevent duplicate prefetch request 118 | self.startedTime = CFAbsoluteTimeGetCurrent(); 119 | self.prefetchURLs = urls; 120 | self.completionBlock = completionBlock; 121 | self.progressBlock = progressBlock; 122 | 123 | if(urls.count == 0){ 124 | if(completionBlock){ 125 | completionBlock(0,0); 126 | } 127 | }else{ 128 | // Starts prefetching from the very first image on the list with the max allowed concurrency 129 | NSUInteger listCount = self.prefetchURLs.count; 130 | for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { 131 | [self startPrefetchingAtIndex:i]; 132 | } 133 | } 134 | } 135 | 136 | - (void)cancelPrefetching { 137 | self.prefetchURLs = nil; 138 | self.skippedCount = 0; 139 | self.requestedCount = 0; 140 | self.finishedCount = 0; 141 | [self.manager cancelAll]; 142 | } 143 | 144 | @end 145 | -------------------------------------------------------------------------------- /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 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 61 | if (completedBlock) { 62 | completedBlock(nil, error, SDImageCacheTypeNone, url); 63 | } 64 | }); 65 | 66 | return; 67 | } 68 | 69 | self.imageURLStorage[@(state)] = url; 70 | 71 | __weak UIButton *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) { 78 | [sself setImage:image forState:state]; 79 | } 80 | if (completedBlock && finished) { 81 | completedBlock(image, error, cacheType, url); 82 | } 83 | }); 84 | }]; 85 | [self sd_setImageLoadOperation:operation forState:state]; 86 | } 87 | 88 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { 89 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 90 | } 91 | 92 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { 93 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 94 | } 95 | 96 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 97 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 98 | } 99 | 100 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock { 101 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; 102 | } 103 | 104 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 105 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; 106 | } 107 | 108 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 109 | [self sd_cancelImageLoadForState:state]; 110 | 111 | [self setBackgroundImage:placeholder forState:state]; 112 | 113 | if (url) { 114 | __weak UIButton *wself = self; 115 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 116 | if (!wself) return; 117 | dispatch_main_sync_safe(^{ 118 | __strong UIButton *sself = wself; 119 | if (!sself) return; 120 | if (image) { 121 | [sself setBackgroundImage:image forState:state]; 122 | } 123 | if (completedBlock && finished) { 124 | completedBlock(image, error, cacheType, url); 125 | } 126 | }); 127 | }]; 128 | [self sd_setBackgroundImageLoadOperation:operation forState:state]; 129 | } else { 130 | dispatch_main_async_safe(^{ 131 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 132 | if (completedBlock) { 133 | completedBlock(nil, error, SDImageCacheTypeNone, url); 134 | } 135 | }); 136 | } 137 | } 138 | 139 | - (void)sd_setImageLoadOperation:(id)operation forState:(UIControlState)state { 140 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 141 | } 142 | 143 | - (void)sd_cancelImageLoadForState:(UIControlState)state { 144 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 145 | } 146 | 147 | - (void)sd_setBackgroundImageLoadOperation:(id)operation forState:(UIControlState)state { 148 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 149 | } 150 | 151 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { 152 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 153 | } 154 | 155 | - (NSMutableDictionary *)imageURLStorage { 156 | NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey); 157 | if (!storage) 158 | { 159 | storage = [NSMutableDictionary dictionary]; 160 | objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 161 | } 162 | 163 | return storage; 164 | } 165 | 166 | @end 167 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | 36 | duration += [self sd_frameDurationAtIndex:i source:source]; 37 | 38 | [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; 39 | 40 | CGImageRelease(image); 41 | } 42 | 43 | if (!duration) { 44 | duration = (1.0f / 10.0f) * count; 45 | } 46 | 47 | animatedImage = [UIImage animatedImageWithImages:images duration:duration]; 48 | } 49 | 50 | CFRelease(source); 51 | 52 | return animatedImage; 53 | } 54 | 55 | + (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { 56 | float frameDuration = 0.1f; 57 | CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); 58 | NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; 59 | NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; 60 | 61 | NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; 62 | if (delayTimeUnclampedProp) { 63 | frameDuration = [delayTimeUnclampedProp floatValue]; 64 | } 65 | else { 66 | 67 | NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; 68 | if (delayTimeProp) { 69 | frameDuration = [delayTimeProp floatValue]; 70 | } 71 | } 72 | 73 | // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. 74 | // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify 75 | // a duration of <= 10 ms. See and 76 | // for more information. 77 | 78 | if (frameDuration < 0.011f) { 79 | frameDuration = 0.100f; 80 | } 81 | 82 | CFRelease(cfFrameProperties); 83 | return frameDuration; 84 | } 85 | 86 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name { 87 | CGFloat scale = [UIScreen mainScreen].scale; 88 | 89 | if (scale > 1.0f) { 90 | NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"]; 91 | 92 | NSData *data = [NSData dataWithContentsOfFile:retinaPath]; 93 | 94 | if (data) { 95 | return [UIImage sd_animatedGIFWithData:data]; 96 | } 97 | 98 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 99 | 100 | data = [NSData dataWithContentsOfFile:path]; 101 | 102 | if (data) { 103 | return [UIImage sd_animatedGIFWithData:data]; 104 | } 105 | 106 | return [UIImage imageNamed:name]; 107 | } 108 | else { 109 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 110 | 111 | NSData *data = [NSData dataWithContentsOfFile:path]; 112 | 113 | if (data) { 114 | return [UIImage sd_animatedGIFWithData:data]; 115 | } 116 | 117 | return [UIImage imageNamed:name]; 118 | } 119 | } 120 | 121 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size { 122 | if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) { 123 | return self; 124 | } 125 | 126 | CGSize scaledSize = size; 127 | CGPoint thumbnailPoint = CGPointZero; 128 | 129 | CGFloat widthFactor = size.width / self.size.width; 130 | CGFloat heightFactor = size.height / self.size.height; 131 | CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor; 132 | scaledSize.width = self.size.width * scaleFactor; 133 | scaledSize.height = self.size.height * scaleFactor; 134 | 135 | if (widthFactor > heightFactor) { 136 | thumbnailPoint.y = (size.height - scaledSize.height) * 0.5; 137 | } 138 | else if (widthFactor < heightFactor) { 139 | thumbnailPoint.x = (size.width - scaledSize.width) * 0.5; 140 | } 141 | 142 | NSMutableArray *scaledImages = [NSMutableArray array]; 143 | 144 | UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); 145 | 146 | for (UIImage *image in self.images) { 147 | [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)]; 148 | UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 149 | 150 | [scaledImages addObject:newImage]; 151 | } 152 | 153 | UIGraphicsEndImageContext(); 154 | 155 | return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; 156 | } 157 | 158 | @end 159 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | UIImage *image; 22 | NSString *imageContentType = [NSData sd_contentTypeForImageData:data]; 23 | if ([imageContentType isEqualToString:@"image/gif"]) { 24 | image = [UIImage sd_animatedGIFWithData:data]; 25 | } 26 | #ifdef SD_WEBP 27 | else if ([imageContentType isEqualToString:@"image/webp"]) 28 | { 29 | image = [UIImage sd_imageWithWebPData:data]; 30 | } 31 | #endif 32 | else { 33 | image = [[UIImage alloc] initWithData:data]; 34 | UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; 35 | if (orientation != UIImageOrientationUp) { 36 | image = [UIImage imageWithCGImage:image.CGImage 37 | scale:image.scale 38 | orientation:orientation]; 39 | } 40 | } 41 | 42 | 43 | return image; 44 | } 45 | 46 | 47 | +(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData { 48 | UIImageOrientation result = UIImageOrientationUp; 49 | CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); 50 | if (imageSource) { 51 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); 52 | if (properties) { 53 | CFTypeRef val; 54 | int exifOrientation; 55 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); 56 | if (val) { 57 | CFNumberGetValue(val, kCFNumberIntType, &exifOrientation); 58 | result = [self sd_exifOrientationToiOSOrientation:exifOrientation]; 59 | } // else - if it's not set it remains at up 60 | CFRelease((CFTypeRef) properties); 61 | } else { 62 | //NSLog(@"NO PROPERTIES, FAIL"); 63 | } 64 | CFRelease(imageSource); 65 | } 66 | return result; 67 | } 68 | 69 | #pragma mark EXIF orientation tag converter 70 | // Convert an EXIF image orientation to an iOS one. 71 | // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html 72 | + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation { 73 | UIImageOrientation orientation = UIImageOrientationUp; 74 | switch (exifOrientation) { 75 | case 1: 76 | orientation = UIImageOrientationUp; 77 | break; 78 | 79 | case 3: 80 | orientation = UIImageOrientationDown; 81 | break; 82 | 83 | case 8: 84 | orientation = UIImageOrientationLeft; 85 | break; 86 | 87 | case 6: 88 | orientation = UIImageOrientationRight; 89 | break; 90 | 91 | case 2: 92 | orientation = UIImageOrientationUpMirrored; 93 | break; 94 | 95 | case 4: 96 | orientation = UIImageOrientationDownMirrored; 97 | break; 98 | 99 | case 5: 100 | orientation = UIImageOrientationLeftMirrored; 101 | break; 102 | 103 | case 7: 104 | orientation = UIImageOrientationRightMirrored; 105 | break; 106 | default: 107 | break; 108 | } 109 | return orientation; 110 | } 111 | 112 | 113 | 114 | @end 115 | -------------------------------------------------------------------------------- /SDWebImage/UIImage+WebP.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+WebP.h 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #ifdef SD_WEBP 10 | 11 | #import 12 | 13 | // Fix for issue #416 Undefined symbols for architecture armv7 since WebP introduction when deploying to device 14 | void WebPInitPremultiplyNEON(void); 15 | 16 | void WebPInitUpsamplersNEON(void); 17 | 18 | void VP8DspInitNEON(void); 19 | 20 | @interface UIImage (WebP) 21 | 22 | + (UIImage *)sd_imageWithWebPData:(NSData *)data; 23 | 24 | @end 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /SDWebImage/UIImage+WebP.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+WebP.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #ifdef SD_WEBP 10 | #import "UIImage+WebP.h" 11 | #import "webp/decode.h" 12 | 13 | // Callback for CGDataProviderRelease 14 | static void FreeImageData(void *info, const void *data, size_t size) 15 | { 16 | free((void *)data); 17 | } 18 | 19 | @implementation UIImage (WebP) 20 | 21 | + (UIImage *)sd_imageWithWebPData:(NSData *)data { 22 | WebPDecoderConfig config; 23 | if (!WebPInitDecoderConfig(&config)) { 24 | return nil; 25 | } 26 | 27 | if (WebPGetFeatures(data.bytes, data.length, &config.input) != VP8_STATUS_OK) { 28 | return nil; 29 | } 30 | 31 | config.output.colorspace = config.input.has_alpha ? MODE_rgbA : MODE_RGB; 32 | config.options.use_threads = 1; 33 | 34 | // Decode the WebP image data into a RGBA value array. 35 | if (WebPDecode(data.bytes, data.length, &config) != VP8_STATUS_OK) { 36 | return nil; 37 | } 38 | 39 | int width = config.input.width; 40 | int height = config.input.height; 41 | if (config.options.use_scaling) { 42 | width = config.options.scaled_width; 43 | height = config.options.scaled_height; 44 | } 45 | 46 | // Construct a UIImage from the decoded RGBA value array. 47 | CGDataProviderRef provider = 48 | CGDataProviderCreateWithData(NULL, config.output.u.RGBA.rgba, config.output.u.RGBA.size, FreeImageData); 49 | CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); 50 | CGBitmapInfo bitmapInfo = config.input.has_alpha ? kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast : 0; 51 | size_t components = config.input.has_alpha ? 4 : 3; 52 | CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; 53 | CGImageRef imageRef = CGImageCreate(width, height, 8, components * 8, components * width, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent); 54 | 55 | CGColorSpaceRelease(colorSpaceRef); 56 | CGDataProviderRelease(provider); 57 | 58 | UIImage *image = [[UIImage alloc] initWithCGImage:imageRef]; 59 | CGImageRelease(imageRef); 60 | 61 | return image; 62 | } 63 | 64 | @end 65 | 66 | #if !COCOAPODS 67 | // Functions to resolve some undefined symbols when using WebP and force_load flag 68 | void WebPInitPremultiplyNEON(void) {} 69 | void WebPInitUpsamplersNEON(void) {} 70 | void VP8DspInitNEON(void) {} 71 | #endif 72 | 73 | #endif 74 | -------------------------------------------------------------------------------- /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 retrived 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 retrived 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 retrived 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 | -------------------------------------------------------------------------------- /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 UIImageView *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) { 43 | wself.highlightedImage = image; 44 | [wself setNeedsLayout]; 45 | } 46 | if (completedBlock && finished) { 47 | completedBlock(image, error, cacheType, url); 48 | } 49 | }); 50 | }]; 51 | [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey]; 52 | } else { 53 | dispatch_main_async_safe(^{ 54 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 55 | if (completedBlock) { 56 | completedBlock(nil, error, SDImageCacheTypeNone, url); 57 | } 58 | }); 59 | } 60 | } 61 | 62 | - (void)sd_cancelCurrentHighlightedImageLoad { 63 | [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey]; 64 | } 65 | 66 | @end 67 | -------------------------------------------------------------------------------- /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 retrived 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 retrived 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 retrived 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 retrived 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 a optionaly 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 retrived from the local cache or from the network. 161 | * The fourth parameter is the original image url. 162 | */ 163 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(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 | @end 180 | -------------------------------------------------------------------------------- /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 | 15 | @implementation UIImageView (WebCache) 16 | 17 | - (void)sd_setImageWithURL:(NSURL *)url { 18 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; 19 | } 20 | 21 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 22 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; 23 | } 24 | 25 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 26 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 27 | } 28 | 29 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 30 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; 31 | } 32 | 33 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 34 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; 35 | } 36 | 37 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 38 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; 39 | } 40 | 41 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 42 | [self sd_cancelCurrentImageLoad]; 43 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 44 | 45 | if (!(options & SDWebImageDelayPlaceholder)) { 46 | dispatch_main_async_safe(^{ 47 | self.image = placeholder; 48 | }); 49 | } 50 | 51 | if (url) { 52 | __weak UIImageView *wself = self; 53 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 54 | if (!wself) return; 55 | dispatch_main_sync_safe(^{ 56 | if (!wself) return; 57 | if (image) { 58 | wself.image = image; 59 | [wself setNeedsLayout]; 60 | } else { 61 | if ((options & SDWebImageDelayPlaceholder)) { 62 | wself.image = placeholder; 63 | [wself setNeedsLayout]; 64 | } 65 | } 66 | if (completedBlock && finished) { 67 | completedBlock(image, error, cacheType, url); 68 | } 69 | }); 70 | }]; 71 | [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"]; 72 | } else { 73 | dispatch_main_async_safe(^{ 74 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 75 | if (completedBlock) { 76 | completedBlock(nil, error, SDImageCacheTypeNone, url); 77 | } 78 | }); 79 | } 80 | } 81 | 82 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 83 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; 84 | UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key]; 85 | 86 | [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; 87 | } 88 | 89 | - (NSURL *)sd_imageURL { 90 | return objc_getAssociatedObject(self, &imageURLKey); 91 | } 92 | 93 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { 94 | [self sd_cancelCurrentAnimationImagesLoad]; 95 | __weak UIImageView *wself = self; 96 | 97 | NSMutableArray *operationsArray = [[NSMutableArray alloc] init]; 98 | 99 | for (NSURL *logoImageURL in arrayOfURLs) { 100 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 101 | if (!wself) return; 102 | dispatch_main_sync_safe(^{ 103 | __strong UIImageView *sself = wself; 104 | [sself stopAnimating]; 105 | if (sself && image) { 106 | NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; 107 | if (!currentImages) { 108 | currentImages = [[NSMutableArray alloc] init]; 109 | } 110 | [currentImages addObject:image]; 111 | 112 | sself.animationImages = currentImages; 113 | [sself setNeedsLayout]; 114 | } 115 | [sself startAnimating]; 116 | }); 117 | }]; 118 | [operationsArray addObject:operation]; 119 | } 120 | 121 | [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"]; 122 | } 123 | 124 | - (void)sd_cancelCurrentImageLoad { 125 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"]; 126 | } 127 | 128 | - (void)sd_cancelCurrentAnimationImagesLoad { 129 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; 130 | } 131 | 132 | @end 133 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /shufflingDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /shufflingDemo.xcodeproj/project.xcworkspace/xcuserdata/yangxin.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yangxiniOS/SlidingPositive/05877e53683f165b8dd2ec1cf292f0c3edc14b6a/shufflingDemo.xcodeproj/project.xcworkspace/xcuserdata/yangxin.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /shufflingDemo.xcodeproj/xcuserdata/yangxin.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /shufflingDemo.xcodeproj/xcuserdata/yangxin.xcuserdatad/xcschemes/shufflingDemo.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 49 | 50 | 51 | 52 | 53 | 54 | 64 | 66 | 72 | 73 | 74 | 75 | 76 | 77 | 83 | 85 | 91 | 92 | 93 | 94 | 96 | 97 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /shufflingDemo.xcodeproj/xcuserdata/yangxin.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | shufflingDemo.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 0D2F46771DDDAB4D0075AF07 16 | 17 | primary 18 | 19 | 20 | 0D2F46901DDDAB4D0075AF07 21 | 22 | primary 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /shufflingDemo/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // shufflingDemo 4 | // 5 | // Created by 杨鑫 on 2016/11/17. 6 | // Copyright © 2016年 Mr Yang. 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 | -------------------------------------------------------------------------------- /shufflingDemo/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // shufflingDemo 4 | // 5 | // Created by 杨鑫 on 2016/11/17. 6 | // Copyright © 2016年 Mr Yang. 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 | // Override point for customization after application launch. 20 | return YES; 21 | } 22 | 23 | - (void)applicationWillResignActive:(UIApplication *)application { 24 | // 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. 25 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 26 | } 27 | 28 | - (void)applicationDidEnterBackground:(UIApplication *)application { 29 | // 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. 30 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 31 | } 32 | 33 | - (void)applicationWillEnterForeground:(UIApplication *)application { 34 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 35 | } 36 | 37 | - (void)applicationDidBecomeActive:(UIApplication *)application { 38 | // 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. 39 | } 40 | 41 | - (void)applicationWillTerminate:(UIApplication *)application { 42 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 43 | } 44 | 45 | @end 46 | -------------------------------------------------------------------------------- /shufflingDemo/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "ipad", 35 | "size" : "29x29", 36 | "scale" : "1x" 37 | }, 38 | { 39 | "idiom" : "ipad", 40 | "size" : "29x29", 41 | "scale" : "2x" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "size" : "40x40", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "size" : "40x40", 51 | "scale" : "2x" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "size" : "76x76", 56 | "scale" : "1x" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "size" : "76x76", 61 | "scale" : "2x" 62 | }, 63 | { 64 | "idiom" : "ipad", 65 | "size" : "83.5x83.5", 66 | "scale" : "2x" 67 | } 68 | ], 69 | "info" : { 70 | "version" : 1, 71 | "author" : "xcode" 72 | } 73 | } -------------------------------------------------------------------------------- /shufflingDemo/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 | -------------------------------------------------------------------------------- /shufflingDemo/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 | -------------------------------------------------------------------------------- /shufflingDemo/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 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIMainStoryboardFile 28 | Main 29 | UIRequiredDeviceCapabilities 30 | 31 | armv7 32 | 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | UIInterfaceOrientationLandscapeLeft 37 | UIInterfaceOrientationLandscapeRight 38 | 39 | UISupportedInterfaceOrientations~ipad 40 | 41 | UIInterfaceOrientationPortrait 42 | UIInterfaceOrientationPortraitUpsideDown 43 | UIInterfaceOrientationLandscapeLeft 44 | UIInterfaceOrientationLandscapeRight 45 | 46 | NSAppTransportSecurity 47 | 48 | NSAllowsArbitraryLoads 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /shufflingDemo/MKShufflingView.h: -------------------------------------------------------------------------------- 1 | // 2 | // MKShufflingView.h 3 | // lianxiceshi 4 | // 5 | // Created by 杨鑫 on 2016/11/16. 6 | // Copyright © 2016年 杨鑫. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "MKpageStyle.h" 11 | 12 | /** 13 | * 展示样式 14 | */ 15 | typedef NS_ENUM(NSInteger, shufflingViewShowstyle) { 16 | /** 17 | * 文字轮播形式 18 | */ 19 | shufflingViewShowstyleText= 0, 20 | /** 21 | * 图片轮播形式 22 | */ 23 | shufflingViewShowstyleImageView, 24 | /** 25 | * 自定义view形式 26 | */ 27 | shufflingViewShowstyleView 28 | }; 29 | /** 30 | * 滑动样式 31 | */ 32 | typedef NS_ENUM(NSInteger, slidingDirection) { 33 | /** 34 | * 水平滑动 35 | */ 36 | slidingDirectionH = 0, 37 | /** 38 | * 数值滑动 39 | */ 40 | slidingDirectionV 41 | }; 42 | /** 43 | * 正反方向 44 | */ 45 | typedef NS_ENUM(NSInteger, slidingPositiveOrNegative) { 46 | /** 47 | * 正方向 48 | */ 49 | slidingPositive = 0, 50 | /** 51 | * 反方向 52 | */ 53 | slidingNegative 54 | }; 55 | 56 | 57 | @interface MKShufflingView : UIView 58 | /** 59 | * 当前传入过来的字符串数组 60 | */ 61 | @property (nonatomic,strong)NSArray *textArray; 62 | /** 63 | * 显示文本 目前只支持pageControl 居上下且原点局左右 如果该数组不为空则判断需要显示文本指示器 64 | */ 65 | @property (nonatomic,strong)NSArray *titleArray; 66 | /** 67 | * 传入的是图片地址 如果是网络图片必须设置为yes,依赖第三方SDWebImage 默认为非为加载本地图片 68 | */ 69 | @property (nonatomic,assign) BOOL isUrlImage; 70 | /** 71 | * 如果是文字轮播文字颜色 72 | */ 73 | @property (nonatomic,strong) UIColor *textColor; 74 | /** 75 | * 设置请求图片展位图 76 | */ 77 | @property (nonatomic,strong)UIImage *placeholderImage; 78 | /** 79 | * 是否自动滚动 默认关闭滚动 为no 80 | */ 81 | @property (nonatomic,assign) BOOL isAutomatic; 82 | /** 83 | * 设置当前所展示的是哪个 默认为0 84 | */ 85 | @property (nonatomic,assign)NSInteger selected; 86 | /** 87 | * 设置当前倒计时时间 默认5秒 88 | */ 89 | @property (nonatomic,assign)NSInteger countdown; 90 | /** 91 | * 样式(如果想要PageControl必传) 92 | */ 93 | @property (nonatomic,strong)MKpageStyle *mypageStyle; 94 | /** 95 | * 是否需要PageControl(如果想要PageControl必传yes 默认为no) 96 | */ 97 | @property (nonatomic,assign) BOOL isShowMyPage; 98 | /** 99 | * 滑动方向 100 | */ 101 | @property (nonatomic,assign)slidingDirection MYslidingDirection; 102 | /** 103 | * 内容样式 104 | */ 105 | @property (nonatomic,assign)shufflingViewShowstyle MYshufflingViewShowstyle; 106 | /** 107 | * 正反方向 108 | */ 109 | @property (nonatomic,assign)slidingPositiveOrNegative MYslidingPositiveOrNegative; 110 | /** 111 | * 滑动完毕执行的block 112 | */ 113 | @property (nonatomic,copy)void (^slidingOverBlock)(NSInteger selected); 114 | /** 115 | * 点击事件 116 | */ 117 | @property (nonatomic,copy)void (^openDownBlock)(NSInteger selected); 118 | /** 119 | * 初始化 120 | * 121 | * @param completion 点击哪一个 122 | */ 123 | - (void)initShufflingView:(void (^)(NSInteger selected))completion; 124 | /** 125 | * 更新显示 126 | */ 127 | - (void)updateMyShufflingView; 128 | @end 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | /** 137 | * 自定义PageControl 138 | */ 139 | @interface MKMyPageControl : UIControl 140 | 141 | 142 | @property (nonatomic,strong)MKpageStyle *mypageStyle; 143 | 144 | @property (nonatomic,strong)NSArray *textArray; 145 | 146 | @property (nonatomic,strong)NSArray *titleArray; 147 | 148 | @property (nonatomic,assign)NSInteger current; 149 | 150 | @property (nonatomic,copy)void (^myFunction)(BOOL isSequence); 151 | - (void)initMKMyPageControlView; 152 | @end 153 | 154 | 155 | 156 | @interface MKGetView : UIView 157 | 158 | @end 159 | 160 | -------------------------------------------------------------------------------- /shufflingDemo/MKpageStyle.h: -------------------------------------------------------------------------------- 1 | // 2 | // MKpageStyle.h 3 | // shufflingDemo 4 | // 5 | // Created by 杨鑫 on 2016/11/18. 6 | // Copyright © 2016年 Mr Yang. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | 13 | 14 | 15 | 16 | /** 17 | * page的位置 18 | */ 19 | typedef NS_ENUM(NSInteger, MKPageStyleLocation) { 20 | /** 21 | * 居下 22 | */ 23 | MKpageStyleLocationBottom = 0, 24 | /** 25 | * 居上 26 | */ 27 | MKpageStyleLocationUp, 28 | /** 29 | * 居左 30 | */ 31 | MKpageStyleLocationLeft, 32 | /** 33 | * 居右 34 | */ 35 | MKpageStyleLocationRight, 36 | }; 37 | /** 38 | * page圆点的位置 39 | */ 40 | typedef NS_ENUM(NSInteger, MKDotStyleLocation) { 41 | /** 42 | * 居中 43 | */ 44 | MKDotStyleLocationCenter = 0, 45 | /** 46 | * 居边 47 | */ 48 | MKDotStyleLocationLeft, 49 | /** 50 | * 居右 51 | */ 52 | MKDotStyleLocationRight 53 | }; 54 | /** 55 | * 圆点格式 56 | */ 57 | typedef NS_ENUM(NSInteger, MKDotFillStyle) { 58 | /** 59 | * 图片指示 60 | */ 61 | MKDotStyleImage = 0, 62 | /** 63 | * 文字指示 64 | */ 65 | MKDotStyleText, 66 | 67 | }; 68 | @interface MKpageStyle : NSObject 69 | /** 70 | * 圆点大小 71 | */ 72 | @property (nonatomic,assign)CGSize styleSize; 73 | /** 74 | * 居page边界多少 由myPageStyle决定 只针对对据左据右 居中时设置此值无效 默认为20 75 | */ 76 | @property (nonatomic,assign)CGFloat constant; 77 | 78 | /** 79 | * 选中的圆点大小 80 | */ 81 | @property (nonatomic,assign)CGSize currentSize; 82 | /** 83 | * 圆角大小 84 | */ 85 | @property (nonatomic,assign)CGFloat roundedCorners; 86 | /** 87 | * 选中圆角大小 88 | */ 89 | @property (nonatomic,assign)CGFloat currentRoundedCorners; 90 | /** 91 | * 文本距离边界多少 显示文本 目前只支持pageControl 居上下且原点局左右 设置有效 92 | */ 93 | @property (nonatomic,assign)CGFloat border; 94 | /** 95 | * 圆点之间的间距 96 | */ 97 | @property (nonatomic,assign)CGFloat spacingValue; 98 | /** 99 | * page的整体高度 或者宽度 由page的位置来确定 100 | */ 101 | @property (nonatomic,assign)CGFloat pageHeight; 102 | /** 103 | * 当前选中的第几个 104 | */ 105 | @property (nonatomic,assign)NSInteger currentValue; 106 | /** 107 | * 圆点图片 108 | */ 109 | @property (nonatomic,strong)UIImage *styleImage; 110 | /** 111 | * 选中的圆点图片 112 | */ 113 | @property (nonatomic,strong)UIImage *currentImage; 114 | /** 115 | * 圆点的位置 116 | */ 117 | @property (nonatomic,assign)MKDotStyleLocation myDotStyle; 118 | /** 119 | * page的位置 120 | */ 121 | @property (nonatomic,assign)MKPageStyleLocation myPageStyle; 122 | /** 123 | * 圆点样式 124 | */ 125 | @property (nonatomic,assign)MKDotFillStyle myDotFillStyle; 126 | /** 127 | * page距离边界多少 128 | */ 129 | @property (nonatomic,assign)CGFloat distance; 130 | /** 131 | * page背景颜色 132 | */ 133 | @property (nonatomic,strong)UIColor *backGroundColor; 134 | /** 135 | * 圆点颜色 136 | */ 137 | @property (nonatomic,strong)UIColor *styleColor; 138 | /** 139 | * 选中圆点颜色 140 | */ 141 | @property (nonatomic,strong)UIColor *currentColor; 142 | /** 143 | * 圆点文字颜色 144 | */ 145 | @property (nonatomic,strong)UIColor *styleTextColor; 146 | /** 147 | * 选中圆点文字颜色 148 | */ 149 | @property (nonatomic,strong)UIColor *currentTextColor; 150 | /** 151 | * 是否支持点击切换 默认支持 152 | */ 153 | @property (nonatomic,assign)BOOL isClick; 154 | /** 155 | * 文本颜色 显示文本 目前只支持pageControl 居上下且原点局左右 设置有效 156 | */ 157 | @property (nonatomic,strong)UIColor *titleColor; 158 | /** 159 | * 设置此值标示当前指示器是对应的文本 只有设置圆点格式为MKDotStyleText有效 160 | */ 161 | @property (nonatomic,strong)NSArray *titleArray; 162 | /** 163 | * 只有设置圆点格式为MKDotStyleText有效 设置文本大小 164 | */ 165 | @property (nonatomic,assign)CGFloat fount; 166 | 167 | @end 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | @interface UIButton (UIButtonExtention) 176 | 177 | 178 | 179 | @property (strong, nonatomic) UIView *extentionView; 180 | 181 | 182 | @end 183 | 184 | 185 | 186 | 187 | 188 | 189 | @interface NSTimer (NSTimerExtention) 190 | + (NSTimer *)ez_scheduledTimerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats; 191 | + (NSTimer *)ez_timerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats; 192 | + (void)__executeTimerBlock:(NSTimer *)inTimer; 193 | @end 194 | 195 | 196 | -------------------------------------------------------------------------------- /shufflingDemo/MKpageStyle.m: -------------------------------------------------------------------------------- 1 | // 2 | // MKpageStyle.m 3 | // shufflingDemo 4 | // 5 | // Created by 杨鑫 on 2016/11/18. 6 | // Copyright © 2016年 Mr Yang. All rights reserved. 7 | // 8 | 9 | #import "MKpageStyle.h" 10 | #import "MKShufflingView.h" 11 | 12 | 13 | 14 | @implementation MKpageStyle 15 | 16 | 17 | - (instancetype)init 18 | { 19 | self = [super init]; 20 | if (self) { 21 | 22 | [self defaultStyle]; 23 | } 24 | return self; 25 | } 26 | 27 | - (void)defaultStyle{ 28 | /** 29 | * 圆点大小 30 | */ 31 | self.styleSize = CGSizeMake(10, 10); 32 | /** 33 | * 圆角大小 34 | */ 35 | self.roundedCorners = 5.f; 36 | /** 37 | * 选中圆角大小 38 | */ 39 | self.currentRoundedCorners = 5.f; 40 | /** 41 | * 文本距离边界多少 显示文本 目前只支持pageControl 居上下且原点局左右 设置有效 42 | */ 43 | self.border = 12; 44 | /** 45 | * 圆点之间的间距 46 | */ 47 | self.spacingValue = 10; 48 | /** 49 | * 选中的圆点大小 50 | */ 51 | self.currentSize = CGSizeMake(10, 10); 52 | /** 53 | * page的整体高度 54 | */ 55 | self.pageHeight = 20; 56 | /** 57 | * 居page边界多少 由myPageStyle决定 只针对对据左据右 居中时设置此值无效 58 | */ 59 | self.constant = 20; 60 | /** 61 | * 圆点的位置 62 | */ 63 | self.myDotStyle = MKDotStyleLocationCenter; 64 | /** 65 | * page的位置 66 | */ 67 | self.myPageStyle = MKpageStyleLocationBottom; 68 | /** 69 | * page距离边界多少 70 | */ 71 | self.distance = 0; 72 | /** 73 | * page背景颜色 74 | */ 75 | self.backGroundColor = [UIColor grayColor]; 76 | /** 77 | * 圆点颜色 78 | */ 79 | self.styleColor = [UIColor whiteColor]; 80 | /** 81 | * 选中圆点颜色 82 | */ 83 | self.currentColor = [UIColor greenColor]; 84 | /** 85 | * 文字字体颜色 86 | */ 87 | self.styleTextColor = [UIColor blackColor]; 88 | /** 89 | * 选中文字字体颜色 90 | */ 91 | self.currentTextColor = [UIColor whiteColor]; 92 | /** 93 | * 是否支持点击切换 94 | */ 95 | self.isClick = YES; 96 | /** 97 | * 文本颜色 显示文本 目前只支持pageControl 居上下且原点局左右 设置有效 98 | */ 99 | self.titleColor = [UIColor whiteColor]; 100 | /** 101 | * 只有设置圆点格式为MKDotStyleText有效 设置文本大小 102 | */ 103 | self.fount = 14; 104 | } 105 | @end 106 | 107 | #import 108 | 109 | 110 | 111 | @class MKGetView; 112 | @implementation UIButton (UIbuttonExtention) 113 | 114 | 115 | 116 | static char *UIbuttonNameKey = "UIbuttonNameKey"; 117 | - (void)setExtentionView:(UIView *)extentionView{ 118 | objc_setAssociatedObject(self, UIbuttonNameKey, extentionView, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 119 | for (MKGetView *view in self.subviews) { 120 | [view removeFromSuperview]; 121 | } 122 | extentionView.userInteractionEnabled = NO; 123 | extentionView.frame = self.bounds; 124 | [self addSubview:extentionView]; 125 | } 126 | - (UIView *)extentionView{ 127 | return objc_getAssociatedObject(self, UIbuttonNameKey); 128 | } 129 | @end 130 | 131 | 132 | @implementation NSTimer (NSTimerExtention) 133 | 134 | + (NSTimer *)ez_scheduledTimerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats 135 | { 136 | void (^block)() = [inBlock copy]; 137 | NSTimer * timer = [self scheduledTimerWithTimeInterval:inTimeInterval target:self selector:@selector(__executeTimerBlock:) userInfo:block repeats:inRepeats]; 138 | return timer; 139 | } 140 | 141 | + (NSTimer *)ez_timerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats 142 | { 143 | void (^block)() = [inBlock copy]; 144 | NSTimer * timer = [self timerWithTimeInterval:inTimeInterval target:self selector:@selector(__executeTimerBlock:) userInfo:block repeats:inRepeats]; 145 | return timer; 146 | } 147 | 148 | + (void)__executeTimerBlock:(NSTimer *)inTimer 149 | { 150 | if([inTimer userInfo]) 151 | { 152 | void (^block)() = (void (^)())[inTimer userInfo]; 153 | block(); 154 | } 155 | } 156 | @end 157 | 158 | -------------------------------------------------------------------------------- /shufflingDemo/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 | -------------------------------------------------------------------------------- /shufflingDemo/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 | -------------------------------------------------------------------------------- /shufflingDemo/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 | * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. 41 | */ 42 | @property (assign, nonatomic) NSUInteger maxMemoryCost; 43 | 44 | /** 45 | * The maximum length of time to keep an image in the cache, in seconds 46 | */ 47 | @property (assign, nonatomic) NSInteger maxCacheAge; 48 | 49 | /** 50 | * The maximum size of the cache, in bytes. 51 | */ 52 | @property (assign, nonatomic) NSUInteger maxCacheSize; 53 | 54 | /** 55 | * Returns global shared cache instance 56 | * 57 | * @return SDImageCache global instance 58 | */ 59 | + (SDImageCache *)sharedImageCache; 60 | 61 | /** 62 | * Init a new cache store with a specific namespace 63 | * 64 | * @param ns The namespace to use for this cache store 65 | */ 66 | - (id)initWithNamespace:(NSString *)ns; 67 | 68 | /** 69 | * Add a read-only cache path to search for images pre-cached by SDImageCache 70 | * Useful if you want to bundle pre-loaded images with your app 71 | * 72 | * @param path The path to use for this read-only cache path 73 | */ 74 | - (void)addReadOnlyCachePath:(NSString *)path; 75 | 76 | /** 77 | * Store an image into memory and disk cache at the given key. 78 | * 79 | * @param image The image to store 80 | * @param key The unique image cache key, usually it's image absolute URL 81 | */ 82 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key; 83 | 84 | /** 85 | * Store an image into memory and optionally disk cache at the given key. 86 | * 87 | * @param image The image to store 88 | * @param key The unique image cache key, usually it's image absolute URL 89 | * @param toDisk Store the image to disk cache if YES 90 | */ 91 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; 92 | 93 | /** 94 | * Store an image into memory and optionally disk cache at the given key. 95 | * 96 | * @param image The image to store 97 | * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage 98 | * @param imageData The image data as returned by the server, this representation will be used for disk storage 99 | * instead of converting the given image object into a storable/compressed image format in order 100 | * to save quality and CPU 101 | * @param key The unique image cache key, usually it's image absolute URL 102 | * @param toDisk Store the image to disk cache if YES 103 | */ 104 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; 105 | 106 | /** 107 | * Query the disk cache asynchronously. 108 | * 109 | * @param key The unique key used to store the wanted image 110 | */ 111 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; 112 | 113 | /** 114 | * Query the memory cache synchronously. 115 | * 116 | * @param key The unique key used to store the wanted image 117 | */ 118 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; 119 | 120 | /** 121 | * Query the disk cache synchronously after checking the memory cache. 122 | * 123 | * @param key The unique key used to store the wanted image 124 | */ 125 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key; 126 | 127 | /** 128 | * Remove the image from memory and disk cache synchronously 129 | * 130 | * @param key The unique image cache key 131 | */ 132 | - (void)removeImageForKey:(NSString *)key; 133 | 134 | 135 | /** 136 | * Remove the image from memory and disk cache synchronously 137 | * 138 | * @param key The unique image cache key 139 | * @param completion An block that should be executed after the image has been removed (optional) 140 | */ 141 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion; 142 | 143 | /** 144 | * Remove the image from memory and optionally disk cache synchronously 145 | * 146 | * @param key The unique image cache key 147 | * @param fromDisk Also remove cache entry from disk if YES 148 | */ 149 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; 150 | 151 | /** 152 | * Remove the image from memory and optionally disk cache synchronously 153 | * 154 | * @param key The unique image cache key 155 | * @param fromDisk Also remove cache entry from disk if YES 156 | * @param completion An block that should be executed after the image has been removed (optional) 157 | */ 158 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion; 159 | 160 | /** 161 | * Clear all memory cached images 162 | */ 163 | - (void)clearMemory; 164 | 165 | /** 166 | * Clear all disk cached images. Non-blocking method - returns immediately. 167 | * @param completion An block that should be executed after cache expiration completes (optional) 168 | */ 169 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion; 170 | 171 | /** 172 | * Clear all disk cached images 173 | * @see clearDiskOnCompletion: 174 | */ 175 | - (void)clearDisk; 176 | 177 | /** 178 | * Remove all expired cached image from disk. Non-blocking method - returns immediately. 179 | * @param completionBlock An block that should be executed after cache expiration completes (optional) 180 | */ 181 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock; 182 | 183 | /** 184 | * Remove all expired cached image from disk 185 | * @see cleanDiskWithCompletionBlock: 186 | */ 187 | - (void)cleanDisk; 188 | 189 | /** 190 | * Get the size used by the disk cache 191 | */ 192 | - (NSUInteger)getSize; 193 | 194 | /** 195 | * Get the number of images in the disk cache 196 | */ 197 | - (NSUInteger)getDiskCount; 198 | 199 | /** 200 | * Asynchronously calculate the disk cache's size. 201 | */ 202 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock; 203 | 204 | /** 205 | * Async check if image exists in disk cache already (does not load the image) 206 | * 207 | * @param key the key describing the url 208 | * @param completionBlock the block to be executed when the check is done. 209 | * @note the completion block will be always executed on the main queue 210 | */ 211 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 212 | 213 | /** 214 | * Check if image exists in disk cache already (does not load the image) 215 | * 216 | * @param key the key describing the url 217 | * 218 | * @return YES if an image exists for the given key 219 | */ 220 | - (BOOL)diskImageExistsWithKey:(NSString *)key; 221 | 222 | /** 223 | * Get the cache path for a certain key (needs the cache path root folder) 224 | * 225 | * @param key the key (can be obtained from url using cacheKeyForURL) 226 | * @param path the cach path root folder 227 | * 228 | * @return the cache path 229 | */ 230 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path; 231 | 232 | /** 233 | * Get the default cache path for a certain key 234 | * 235 | * @param key the key (can be obtained from url using cacheKeyForURL) 236 | * 237 | * @return the default cache path 238 | */ 239 | - (NSString *)defaultCachePathForKey:(NSString *)key; 240 | 241 | @end 242 | -------------------------------------------------------------------------------- /shufflingDemo/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 < __IPHONE_5_0 17 | #error SDWebImage doesn't support Deployement 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 | #define dispatch_main_sync_safe(block)\ 59 | if ([NSThread isMainThread]) {\ 60 | block();\ 61 | } else {\ 62 | dispatch_sync(dispatch_get_main_queue(), block);\ 63 | } 64 | 65 | #define dispatch_main_async_safe(block)\ 66 | if ([NSThread isMainThread]) {\ 67 | block();\ 68 | } else {\ 69 | dispatch_async(dispatch_get_main_queue(), block);\ 70 | } 71 | -------------------------------------------------------------------------------- /shufflingDemo/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.0; 32 | if (key.length >= 8) { 33 | // Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext) 34 | NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)]; 35 | if (range.location != NSNotFound) { 36 | scale = 2.0; 37 | } 38 | } 39 | 40 | UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; 41 | image = scaledImage; 42 | } 43 | return image; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /shufflingDemo/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 | -------------------------------------------------------------------------------- /shufflingDemo/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 | if (image.images) { 17 | // Do not decode animated images 18 | return image; 19 | } 20 | 21 | CGImageRef imageRef = image.CGImage; 22 | CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); 23 | CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; 24 | 25 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 26 | CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); 27 | 28 | int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask); 29 | BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone || 30 | infoMask == kCGImageAlphaNoneSkipFirst || 31 | infoMask == kCGImageAlphaNoneSkipLast); 32 | 33 | // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. 34 | // https://developer.apple.com/library/mac/#qa/qa1037/_index.html 35 | if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) { 36 | // Unset the old alpha info. 37 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 38 | 39 | // Set noneSkipFirst. 40 | bitmapInfo |= kCGImageAlphaNoneSkipFirst; 41 | } 42 | // Some PNGs tell us they have alpha but only 3 components. Odd. 43 | else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { 44 | // Unset the old alpha info. 45 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 46 | bitmapInfo |= kCGImageAlphaPremultipliedFirst; 47 | } 48 | 49 | // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. 50 | CGContextRef context = CGBitmapContextCreate(NULL, 51 | imageSize.width, 52 | imageSize.height, 53 | CGImageGetBitsPerComponent(imageRef), 54 | 0, 55 | colorSpace, 56 | bitmapInfo); 57 | CGColorSpaceRelease(colorSpace); 58 | 59 | // If failed, return undecompressed image 60 | if (!context) return image; 61 | 62 | CGContextDrawImage(context, imageRect, imageRef); 63 | CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); 64 | 65 | CGContextRelease(context); 66 | 67 | UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation]; 68 | CGImageRelease(decompressedImageRef); 69 | return decompressedImage; 70 | } 71 | 72 | @end 73 | -------------------------------------------------------------------------------- /shufflingDemo/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 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 ceriticates. 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 | }; 55 | 56 | typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { 57 | /** 58 | * Default value. All download operations will execute in queue style (first-in-first-out). 59 | */ 60 | SDWebImageDownloaderFIFOExecutionOrder, 61 | 62 | /** 63 | * All download operations will execute in stack style (last-in-first-out). 64 | */ 65 | SDWebImageDownloaderLIFOExecutionOrder 66 | }; 67 | 68 | extern NSString *const SDWebImageDownloadStartNotification; 69 | extern NSString *const SDWebImageDownloadStopNotification; 70 | 71 | typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); 72 | 73 | typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); 74 | 75 | typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers); 76 | 77 | /** 78 | * Asynchronous downloader dedicated and optimized for image loading. 79 | */ 80 | @interface SDWebImageDownloader : NSObject 81 | 82 | @property (assign, nonatomic) NSInteger maxConcurrentDownloads; 83 | 84 | /** 85 | * Shows the current amount of downloads that still need to be downloaded 86 | */ 87 | 88 | @property (readonly, nonatomic) NSUInteger currentDownloadCount; 89 | 90 | 91 | /** 92 | * The timeout value (in seconds) for the download operation. Default: 15.0. 93 | */ 94 | @property (assign, nonatomic) NSTimeInterval downloadTimeout; 95 | 96 | 97 | /** 98 | * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. 99 | */ 100 | @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; 101 | 102 | /** 103 | * Singleton method, returns the shared instance 104 | * 105 | * @return global shared instance of downloader class 106 | */ 107 | + (SDWebImageDownloader *)sharedDownloader; 108 | 109 | /** 110 | * Set username 111 | */ 112 | @property (strong, nonatomic) NSString *username; 113 | 114 | /** 115 | * Set password 116 | */ 117 | @property (strong, nonatomic) NSString *password; 118 | 119 | /** 120 | * Set filter to pick headers for downloading image HTTP request. 121 | * 122 | * This block will be invoked for each downloading image request, returned 123 | * NSDictionary will be used as headers in corresponding HTTP request. 124 | */ 125 | @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter; 126 | 127 | /** 128 | * Set a value for a HTTP header to be appended to each download HTTP request. 129 | * 130 | * @param value The value for the header field. Use `nil` value to remove the header. 131 | * @param field The name of the header field to set. 132 | */ 133 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; 134 | 135 | /** 136 | * Returns the value of the specified HTTP header field. 137 | * 138 | * @return The value associated with the header field field, or `nil` if there is no corresponding header field. 139 | */ 140 | - (NSString *)valueForHTTPHeaderField:(NSString *)field; 141 | 142 | /** 143 | * Sets a subclass of `SDWebImageDownloaderOperation` as the default 144 | * `NSOperation` to be used each time SDWebImage constructs a request 145 | * operation to download an image. 146 | * 147 | * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set 148 | * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. 149 | */ 150 | - (void)setOperationClass:(Class)operationClass; 151 | 152 | /** 153 | * Creates a SDWebImageDownloader async downloader instance with a given URL 154 | * 155 | * The delegate will be informed when the image is finish downloaded or an error has happen. 156 | * 157 | * @see SDWebImageDownloaderDelegate 158 | * 159 | * @param url The URL to the image to download 160 | * @param options The options to be used for this download 161 | * @param progressBlock A block called repeatedly while the image is downloading 162 | * @param completedBlock A block called once the download is completed. 163 | * If the download succeeded, the image parameter is set, in case of error, 164 | * error parameter is set with the error. The last parameter is always YES 165 | * if SDWebImageDownloaderProgressiveDownload isn't use. With the 166 | * SDWebImageDownloaderProgressiveDownload option, this block is called 167 | * repeatedly with the partial image object and the finished argument set to NO 168 | * before to be called a last time with the full image and finished argument 169 | * set to YES. In case of error, the finished argument is always YES. 170 | * 171 | * @return A cancellable SDWebImageOperation 172 | */ 173 | - (id )downloadImageWithURL:(NSURL *)url 174 | options:(SDWebImageDownloaderOptions)options 175 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 176 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock; 177 | 178 | /** 179 | * Sets the download queue suspension state 180 | */ 181 | - (void)setSuspended:(BOOL)suspended; 182 | 183 | @end 184 | -------------------------------------------------------------------------------- /shufflingDemo/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 | @interface SDWebImageDownloaderOperation : NSOperation 14 | 15 | /** 16 | * The request used by the operation's connection. 17 | */ 18 | @property (strong, nonatomic, readonly) NSURLRequest *request; 19 | 20 | /** 21 | * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. 22 | * 23 | * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. 24 | */ 25 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage; 26 | 27 | /** 28 | * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. 29 | * 30 | * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. 31 | */ 32 | @property (nonatomic, strong) NSURLCredential *credential; 33 | 34 | /** 35 | * The SDWebImageDownloaderOptions for the receiver. 36 | */ 37 | @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; 38 | 39 | /** 40 | * Initializes a `SDWebImageDownloaderOperation` object 41 | * 42 | * @see SDWebImageDownloaderOperation 43 | * 44 | * @param request the URL request 45 | * @param options downloader options 46 | * @param progressBlock the block executed when a new chunk of data arrives. 47 | * @note the progress block is executed on a background queue 48 | * @param completedBlock the block executed when the download is done. 49 | * @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 50 | * @param cancelBlock the block executed if the download (operation) is cancelled 51 | * 52 | * @return the initialized instance 53 | */ 54 | - (id)initWithRequest:(NSURLRequest *)request 55 | options:(SDWebImageDownloaderOptions)options 56 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 57 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock 58 | cancelled:(SDWebImageNoParamsBlock)cancelBlock; 59 | 60 | @end 61 | -------------------------------------------------------------------------------- /shufflingDemo/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 embeded 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 ceriticates. 62 | * Useful for testing purposes. Use with caution in production. 63 | */ 64 | SDWebImageAllowInvalidSSLCertificates = 1 << 7, 65 | 66 | /** 67 | * By default, image are loaded in the order they were queued. This flag move them to 68 | * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which 69 | * could take a while). 70 | */ 71 | SDWebImageHighPriority = 1 << 8, 72 | 73 | /** 74 | * By default, placeholder images are loaded while the image is loading. This flag will delay the loading 75 | * of the placeholder image until after the image has finished loading. 76 | */ 77 | SDWebImageDelayPlaceholder = 1 << 9, 78 | 79 | /** 80 | * We usually don't call transformDownloadedImage delegate method on animated images, 81 | * as most transformation code would mangle it. 82 | * Use this flag to transform them anyway. 83 | */ 84 | SDWebImageTransformAnimatedImage = 1 << 10, 85 | }; 86 | 87 | typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL); 88 | 89 | typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL); 90 | 91 | typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url); 92 | 93 | 94 | @class SDWebImageManager; 95 | 96 | @protocol SDWebImageManagerDelegate 97 | 98 | @optional 99 | 100 | /** 101 | * Controls which image should be downloaded when the image is not found in the cache. 102 | * 103 | * @param imageManager The current `SDWebImageManager` 104 | * @param imageURL The url of the image to be downloaded 105 | * 106 | * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. 107 | */ 108 | - (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; 109 | 110 | /** 111 | * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. 112 | * NOTE: This method is called from a global queue in order to not to block the main thread. 113 | * 114 | * @param imageManager The current `SDWebImageManager` 115 | * @param image The image to transform 116 | * @param imageURL The url of the image to transform 117 | * 118 | * @return The transformed image object. 119 | */ 120 | - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; 121 | 122 | @end 123 | 124 | /** 125 | * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. 126 | * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). 127 | * You can use this class directly to benefit from web image downloading with caching in another context than 128 | * a UIView. 129 | * 130 | * Here is a simple example of how to use SDWebImageManager: 131 | * 132 | * @code 133 | 134 | SDWebImageManager *manager = [SDWebImageManager sharedManager]; 135 | [manager downloadWithURL:imageURL 136 | options:0 137 | progress:nil 138 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 139 | if (image) { 140 | // do something with image 141 | } 142 | }]; 143 | 144 | * @endcode 145 | */ 146 | @interface SDWebImageManager : NSObject 147 | 148 | @property (weak, nonatomic) id delegate; 149 | 150 | @property (strong, nonatomic, readonly) SDImageCache *imageCache; 151 | @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; 152 | 153 | /** 154 | * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can 155 | * be used to remove dynamic part of an image URL. 156 | * 157 | * The following example sets a filter in the application delegate that will remove any query-string from the 158 | * URL before to use it as a cache key: 159 | * 160 | * @code 161 | 162 | [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { 163 | url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; 164 | return [url absoluteString]; 165 | }]; 166 | 167 | * @endcode 168 | */ 169 | @property (nonatomic, copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter; 170 | 171 | /** 172 | * Returns global SDWebImageManager instance. 173 | * 174 | * @return SDWebImageManager shared instance 175 | */ 176 | + (SDWebImageManager *)sharedManager; 177 | 178 | /** 179 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 180 | * 181 | * @param url The URL to the image 182 | * @param options A mask to specify options to use for this request 183 | * @param progressBlock A block called while image is downloading 184 | * @param completedBlock A block called when operation has been completed. 185 | * 186 | * This parameter is required. 187 | * 188 | * This block has no return value and takes the requested UIImage as first parameter. 189 | * In case of error the image parameter is nil and the second parameter may contain an NSError. 190 | * 191 | * The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache 192 | * or from the memory cache or from the network. 193 | * 194 | * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is 195 | * downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the 196 | * block is called a last time with the full image and the last parameter set to YES. 197 | * 198 | * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation 199 | */ 200 | - (id )downloadImageWithURL:(NSURL *)url 201 | options:(SDWebImageOptions)options 202 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 203 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock; 204 | 205 | /** 206 | * Saves image to cache for given URL 207 | * 208 | * @param image The image to cache 209 | * @param url The URL to the image 210 | * 211 | */ 212 | 213 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url; 214 | 215 | /** 216 | * Cancel all current opreations 217 | */ 218 | - (void)cancelAll; 219 | 220 | /** 221 | * Check one or more operations running 222 | */ 223 | - (BOOL)isRunning; 224 | 225 | /** 226 | * Check if image has already been cached 227 | * 228 | * @param url image url 229 | * 230 | * @return if the image was already cached 231 | */ 232 | - (BOOL)cachedImageExistsForURL:(NSURL *)url; 233 | 234 | /** 235 | * Check if image has already been cached on disk only 236 | * 237 | * @param url image url 238 | * 239 | * @return if the image was already cached (disk only) 240 | */ 241 | - (BOOL)diskImageExistsForURL:(NSURL *)url; 242 | 243 | /** 244 | * Async check if image has already been cached 245 | * 246 | * @param url image url 247 | * @param completionBlock the block to be executed when the check is finished 248 | * 249 | * @note the completion block is always executed on the main queue 250 | */ 251 | - (void)cachedImageExistsForURL:(NSURL *)url 252 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 253 | 254 | /** 255 | * Async check if image has already been cached on disk only 256 | * 257 | * @param url image url 258 | * @param completionBlock the block to be executed when the check is finished 259 | * 260 | * @note the completion block is always executed on the main queue 261 | */ 262 | - (void)diskImageExistsForURL:(NSURL *)url 263 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 264 | 265 | 266 | /** 267 | *Return the cache key for a given URL 268 | */ 269 | - (NSString *)cacheKeyForURL:(NSURL *)url; 270 | 271 | @end 272 | -------------------------------------------------------------------------------- /shufflingDemo/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 | -------------------------------------------------------------------------------- /shufflingDemo/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 | @property (weak, nonatomic) id delegate; 62 | 63 | /** 64 | * Return the global image prefetcher instance. 65 | */ 66 | + (SDWebImagePrefetcher *)sharedImagePrefetcher; 67 | 68 | /** 69 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 70 | * currently one image is downloaded at a time, 71 | * and skips images for failed downloads and proceed to the next image in the list 72 | * 73 | * @param urls list of URLs to prefetch 74 | */ 75 | - (void)prefetchURLs:(NSArray *)urls; 76 | 77 | /** 78 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 79 | * currently one image is downloaded at a time, 80 | * and skips images for failed downloads and proceed to the next image in the list 81 | * 82 | * @param urls list of URLs to prefetch 83 | * @param progressBlock block to be called when progress updates; 84 | * first parameter is the number of completed (successful or not) requests, 85 | * second parameter is the total number of images originally requested to be prefetched 86 | * @param completionBlock block to be called when prefetching is completed 87 | * first param is the number of completed (successful or not) requests, 88 | * second parameter is the number of skipped requests 89 | */ 90 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock; 91 | 92 | /** 93 | * Remove and cancel queued list 94 | */ 95 | - (void)cancelPrefetching; 96 | 97 | 98 | @end 99 | -------------------------------------------------------------------------------- /shufflingDemo/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 | #if (!defined(DEBUG) && !defined (SD_VERBOSE)) || defined(SD_LOG_NONE) 12 | #define NSLog(...) 13 | #endif 14 | 15 | @interface SDWebImagePrefetcher () 16 | 17 | @property (strong, nonatomic) SDWebImageManager *manager; 18 | @property (strong, nonatomic) NSArray *prefetchURLs; 19 | @property (assign, nonatomic) NSUInteger requestedCount; 20 | @property (assign, nonatomic) NSUInteger skippedCount; 21 | @property (assign, nonatomic) NSUInteger finishedCount; 22 | @property (assign, nonatomic) NSTimeInterval startedTime; 23 | @property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock; 24 | @property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock; 25 | 26 | @end 27 | 28 | @implementation SDWebImagePrefetcher 29 | 30 | + (SDWebImagePrefetcher *)sharedImagePrefetcher { 31 | static dispatch_once_t once; 32 | static id instance; 33 | dispatch_once(&once, ^{ 34 | instance = [self new]; 35 | }); 36 | return instance; 37 | } 38 | 39 | - (id)init { 40 | if ((self = [super init])) { 41 | _manager = [SDWebImageManager new]; 42 | _options = SDWebImageLowPriority; 43 | self.maxConcurrentDownloads = 3; 44 | } 45 | return self; 46 | } 47 | 48 | - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { 49 | self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; 50 | } 51 | 52 | - (NSUInteger)maxConcurrentDownloads { 53 | return self.manager.imageDownloader.maxConcurrentDownloads; 54 | } 55 | 56 | - (void)startPrefetchingAtIndex:(NSUInteger)index { 57 | if (index >= self.prefetchURLs.count) return; 58 | self.requestedCount++; 59 | [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 60 | if (!finished) return; 61 | self.finishedCount++; 62 | 63 | if (image) { 64 | if (self.progressBlock) { 65 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 66 | } 67 | NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count)); 68 | } 69 | else { 70 | if (self.progressBlock) { 71 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 72 | } 73 | NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count)); 74 | 75 | // Add last failed 76 | self.skippedCount++; 77 | } 78 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { 79 | [self.delegate imagePrefetcher:self 80 | didPrefetchURL:self.prefetchURLs[index] 81 | finishedCount:self.finishedCount 82 | totalCount:self.prefetchURLs.count 83 | ]; 84 | } 85 | 86 | if (self.prefetchURLs.count > self.requestedCount) { 87 | dispatch_async(dispatch_get_main_queue(), ^{ 88 | [self startPrefetchingAtIndex:self.requestedCount]; 89 | }); 90 | } 91 | else if (self.finishedCount == self.requestedCount) { 92 | [self reportStatus]; 93 | if (self.completionBlock) { 94 | self.completionBlock(self.finishedCount, self.skippedCount); 95 | self.completionBlock = nil; 96 | } 97 | } 98 | }]; 99 | } 100 | 101 | - (void)reportStatus { 102 | NSUInteger total = [self.prefetchURLs count]; 103 | NSLog(@"Finished prefetching (%@ successful, %@ skipped, timeElasped %.2f)", @(total - self.skippedCount), @(self.skippedCount), CFAbsoluteTimeGetCurrent() - self.startedTime); 104 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { 105 | [self.delegate imagePrefetcher:self 106 | didFinishWithTotalCount:(total - self.skippedCount) 107 | skippedCount:self.skippedCount 108 | ]; 109 | } 110 | } 111 | 112 | - (void)prefetchURLs:(NSArray *)urls { 113 | [self prefetchURLs:urls progress:nil completed:nil]; 114 | } 115 | 116 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock { 117 | [self cancelPrefetching]; // Prevent duplicate prefetch request 118 | self.startedTime = CFAbsoluteTimeGetCurrent(); 119 | self.prefetchURLs = urls; 120 | self.completionBlock = completionBlock; 121 | self.progressBlock = progressBlock; 122 | 123 | if(urls.count == 0){ 124 | if(completionBlock){ 125 | completionBlock(0,0); 126 | } 127 | }else{ 128 | // Starts prefetching from the very first image on the list with the max allowed concurrency 129 | NSUInteger listCount = self.prefetchURLs.count; 130 | for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { 131 | [self startPrefetchingAtIndex:i]; 132 | } 133 | } 134 | } 135 | 136 | - (void)cancelPrefetching { 137 | self.prefetchURLs = nil; 138 | self.skippedCount = 0; 139 | self.requestedCount = 0; 140 | self.finishedCount = 0; 141 | [self.manager cancelAll]; 142 | } 143 | 144 | @end 145 | -------------------------------------------------------------------------------- /shufflingDemo/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 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 61 | if (completedBlock) { 62 | completedBlock(nil, error, SDImageCacheTypeNone, url); 63 | } 64 | }); 65 | 66 | return; 67 | } 68 | 69 | self.imageURLStorage[@(state)] = url; 70 | 71 | __weak UIButton *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) { 78 | [sself setImage:image forState:state]; 79 | } 80 | if (completedBlock && finished) { 81 | completedBlock(image, error, cacheType, url); 82 | } 83 | }); 84 | }]; 85 | [self sd_setImageLoadOperation:operation forState:state]; 86 | } 87 | 88 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state { 89 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil]; 90 | } 91 | 92 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder { 93 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil]; 94 | } 95 | 96 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 97 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil]; 98 | } 99 | 100 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock { 101 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock]; 102 | } 103 | 104 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 105 | [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock]; 106 | } 107 | 108 | - (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 109 | [self sd_cancelImageLoadForState:state]; 110 | 111 | [self setBackgroundImage:placeholder forState:state]; 112 | 113 | if (url) { 114 | __weak UIButton *wself = self; 115 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 116 | if (!wself) return; 117 | dispatch_main_sync_safe(^{ 118 | __strong UIButton *sself = wself; 119 | if (!sself) return; 120 | if (image) { 121 | [sself setBackgroundImage:image forState:state]; 122 | } 123 | if (completedBlock && finished) { 124 | completedBlock(image, error, cacheType, url); 125 | } 126 | }); 127 | }]; 128 | [self sd_setBackgroundImageLoadOperation:operation forState:state]; 129 | } else { 130 | dispatch_main_async_safe(^{ 131 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 132 | if (completedBlock) { 133 | completedBlock(nil, error, SDImageCacheTypeNone, url); 134 | } 135 | }); 136 | } 137 | } 138 | 139 | - (void)sd_setImageLoadOperation:(id)operation forState:(UIControlState)state { 140 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 141 | } 142 | 143 | - (void)sd_cancelImageLoadForState:(UIControlState)state { 144 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]]; 145 | } 146 | 147 | - (void)sd_setBackgroundImageLoadOperation:(id)operation forState:(UIControlState)state { 148 | [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 149 | } 150 | 151 | - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state { 152 | [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]]; 153 | } 154 | 155 | - (NSMutableDictionary *)imageURLStorage { 156 | NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey); 157 | if (!storage) 158 | { 159 | storage = [NSMutableDictionary dictionary]; 160 | objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 161 | } 162 | 163 | return storage; 164 | } 165 | 166 | @end 167 | -------------------------------------------------------------------------------- /shufflingDemo/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 | -------------------------------------------------------------------------------- /shufflingDemo/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 | 36 | duration += [self sd_frameDurationAtIndex:i source:source]; 37 | 38 | [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; 39 | 40 | CGImageRelease(image); 41 | } 42 | 43 | if (!duration) { 44 | duration = (1.0f / 10.0f) * count; 45 | } 46 | 47 | animatedImage = [UIImage animatedImageWithImages:images duration:duration]; 48 | } 49 | 50 | CFRelease(source); 51 | 52 | return animatedImage; 53 | } 54 | 55 | + (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { 56 | float frameDuration = 0.1f; 57 | CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); 58 | NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; 59 | NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; 60 | 61 | NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; 62 | if (delayTimeUnclampedProp) { 63 | frameDuration = [delayTimeUnclampedProp floatValue]; 64 | } 65 | else { 66 | 67 | NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; 68 | if (delayTimeProp) { 69 | frameDuration = [delayTimeProp floatValue]; 70 | } 71 | } 72 | 73 | // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. 74 | // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify 75 | // a duration of <= 10 ms. See and 76 | // for more information. 77 | 78 | if (frameDuration < 0.011f) { 79 | frameDuration = 0.100f; 80 | } 81 | 82 | CFRelease(cfFrameProperties); 83 | return frameDuration; 84 | } 85 | 86 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name { 87 | CGFloat scale = [UIScreen mainScreen].scale; 88 | 89 | if (scale > 1.0f) { 90 | NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"]; 91 | 92 | NSData *data = [NSData dataWithContentsOfFile:retinaPath]; 93 | 94 | if (data) { 95 | return [UIImage sd_animatedGIFWithData:data]; 96 | } 97 | 98 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 99 | 100 | data = [NSData dataWithContentsOfFile:path]; 101 | 102 | if (data) { 103 | return [UIImage sd_animatedGIFWithData:data]; 104 | } 105 | 106 | return [UIImage imageNamed:name]; 107 | } 108 | else { 109 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 110 | 111 | NSData *data = [NSData dataWithContentsOfFile:path]; 112 | 113 | if (data) { 114 | return [UIImage sd_animatedGIFWithData:data]; 115 | } 116 | 117 | return [UIImage imageNamed:name]; 118 | } 119 | } 120 | 121 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size { 122 | if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) { 123 | return self; 124 | } 125 | 126 | CGSize scaledSize = size; 127 | CGPoint thumbnailPoint = CGPointZero; 128 | 129 | CGFloat widthFactor = size.width / self.size.width; 130 | CGFloat heightFactor = size.height / self.size.height; 131 | CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor; 132 | scaledSize.width = self.size.width * scaleFactor; 133 | scaledSize.height = self.size.height * scaleFactor; 134 | 135 | if (widthFactor > heightFactor) { 136 | thumbnailPoint.y = (size.height - scaledSize.height) * 0.5; 137 | } 138 | else if (widthFactor < heightFactor) { 139 | thumbnailPoint.x = (size.width - scaledSize.width) * 0.5; 140 | } 141 | 142 | NSMutableArray *scaledImages = [NSMutableArray array]; 143 | 144 | UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); 145 | 146 | for (UIImage *image in self.images) { 147 | [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)]; 148 | UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 149 | 150 | [scaledImages addObject:newImage]; 151 | } 152 | 153 | UIGraphicsEndImageContext(); 154 | 155 | return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; 156 | } 157 | 158 | @end 159 | -------------------------------------------------------------------------------- /shufflingDemo/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 | -------------------------------------------------------------------------------- /shufflingDemo/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 | UIImage *image; 22 | NSString *imageContentType = [NSData sd_contentTypeForImageData:data]; 23 | if ([imageContentType isEqualToString:@"image/gif"]) { 24 | image = [UIImage sd_animatedGIFWithData:data]; 25 | } 26 | #ifdef SD_WEBP 27 | else if ([imageContentType isEqualToString:@"image/webp"]) 28 | { 29 | image = [UIImage sd_imageWithWebPData:data]; 30 | } 31 | #endif 32 | else { 33 | image = [[UIImage alloc] initWithData:data]; 34 | UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; 35 | if (orientation != UIImageOrientationUp) { 36 | image = [UIImage imageWithCGImage:image.CGImage 37 | scale:image.scale 38 | orientation:orientation]; 39 | } 40 | } 41 | 42 | 43 | return image; 44 | } 45 | 46 | 47 | +(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData { 48 | UIImageOrientation result = UIImageOrientationUp; 49 | CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); 50 | if (imageSource) { 51 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); 52 | if (properties) { 53 | CFTypeRef val; 54 | int exifOrientation; 55 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); 56 | if (val) { 57 | CFNumberGetValue(val, kCFNumberIntType, &exifOrientation); 58 | result = [self sd_exifOrientationToiOSOrientation:exifOrientation]; 59 | } // else - if it's not set it remains at up 60 | CFRelease((CFTypeRef) properties); 61 | } else { 62 | //NSLog(@"NO PROPERTIES, FAIL"); 63 | } 64 | CFRelease(imageSource); 65 | } 66 | return result; 67 | } 68 | 69 | #pragma mark EXIF orientation tag converter 70 | // Convert an EXIF image orientation to an iOS one. 71 | // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html 72 | + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation { 73 | UIImageOrientation orientation = UIImageOrientationUp; 74 | switch (exifOrientation) { 75 | case 1: 76 | orientation = UIImageOrientationUp; 77 | break; 78 | 79 | case 3: 80 | orientation = UIImageOrientationDown; 81 | break; 82 | 83 | case 8: 84 | orientation = UIImageOrientationLeft; 85 | break; 86 | 87 | case 6: 88 | orientation = UIImageOrientationRight; 89 | break; 90 | 91 | case 2: 92 | orientation = UIImageOrientationUpMirrored; 93 | break; 94 | 95 | case 4: 96 | orientation = UIImageOrientationDownMirrored; 97 | break; 98 | 99 | case 5: 100 | orientation = UIImageOrientationLeftMirrored; 101 | break; 102 | 103 | case 7: 104 | orientation = UIImageOrientationRightMirrored; 105 | break; 106 | default: 107 | break; 108 | } 109 | return orientation; 110 | } 111 | 112 | 113 | 114 | @end 115 | -------------------------------------------------------------------------------- /shufflingDemo/SDWebImage/UIImage+WebP.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+WebP.h 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #ifdef SD_WEBP 10 | 11 | #import 12 | 13 | // Fix for issue #416 Undefined symbols for architecture armv7 since WebP introduction when deploying to device 14 | void WebPInitPremultiplyNEON(void); 15 | 16 | void WebPInitUpsamplersNEON(void); 17 | 18 | void VP8DspInitNEON(void); 19 | 20 | @interface UIImage (WebP) 21 | 22 | + (UIImage *)sd_imageWithWebPData:(NSData *)data; 23 | 24 | @end 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /shufflingDemo/SDWebImage/UIImage+WebP.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+WebP.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #ifdef SD_WEBP 10 | #import "UIImage+WebP.h" 11 | #import "webp/decode.h" 12 | 13 | // Callback for CGDataProviderRelease 14 | static void FreeImageData(void *info, const void *data, size_t size) 15 | { 16 | free((void *)data); 17 | } 18 | 19 | @implementation UIImage (WebP) 20 | 21 | + (UIImage *)sd_imageWithWebPData:(NSData *)data { 22 | WebPDecoderConfig config; 23 | if (!WebPInitDecoderConfig(&config)) { 24 | return nil; 25 | } 26 | 27 | if (WebPGetFeatures(data.bytes, data.length, &config.input) != VP8_STATUS_OK) { 28 | return nil; 29 | } 30 | 31 | config.output.colorspace = config.input.has_alpha ? MODE_rgbA : MODE_RGB; 32 | config.options.use_threads = 1; 33 | 34 | // Decode the WebP image data into a RGBA value array. 35 | if (WebPDecode(data.bytes, data.length, &config) != VP8_STATUS_OK) { 36 | return nil; 37 | } 38 | 39 | int width = config.input.width; 40 | int height = config.input.height; 41 | if (config.options.use_scaling) { 42 | width = config.options.scaled_width; 43 | height = config.options.scaled_height; 44 | } 45 | 46 | // Construct a UIImage from the decoded RGBA value array. 47 | CGDataProviderRef provider = 48 | CGDataProviderCreateWithData(NULL, config.output.u.RGBA.rgba, config.output.u.RGBA.size, FreeImageData); 49 | CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); 50 | CGBitmapInfo bitmapInfo = config.input.has_alpha ? kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast : 0; 51 | size_t components = config.input.has_alpha ? 4 : 3; 52 | CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; 53 | CGImageRef imageRef = CGImageCreate(width, height, 8, components * 8, components * width, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent); 54 | 55 | CGColorSpaceRelease(colorSpaceRef); 56 | CGDataProviderRelease(provider); 57 | 58 | UIImage *image = [[UIImage alloc] initWithCGImage:imageRef]; 59 | CGImageRelease(imageRef); 60 | 61 | return image; 62 | } 63 | 64 | @end 65 | 66 | #if !COCOAPODS 67 | // Functions to resolve some undefined symbols when using WebP and force_load flag 68 | void WebPInitPremultiplyNEON(void) {} 69 | void WebPInitUpsamplersNEON(void) {} 70 | void VP8DspInitNEON(void) {} 71 | #endif 72 | 73 | #endif 74 | -------------------------------------------------------------------------------- /shufflingDemo/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 retrived 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 retrived 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 retrived 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 | -------------------------------------------------------------------------------- /shufflingDemo/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 UIImageView *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) { 43 | wself.highlightedImage = image; 44 | [wself setNeedsLayout]; 45 | } 46 | if (completedBlock && finished) { 47 | completedBlock(image, error, cacheType, url); 48 | } 49 | }); 50 | }]; 51 | [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey]; 52 | } else { 53 | dispatch_main_async_safe(^{ 54 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 55 | if (completedBlock) { 56 | completedBlock(nil, error, SDImageCacheTypeNone, url); 57 | } 58 | }); 59 | } 60 | } 61 | 62 | - (void)sd_cancelCurrentHighlightedImageLoad { 63 | [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey]; 64 | } 65 | 66 | @end 67 | -------------------------------------------------------------------------------- /shufflingDemo/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 retrived 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 retrived 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 retrived 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 retrived 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 a optionaly 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 retrived from the local cache or from the network. 161 | * The fourth parameter is the original image url. 162 | */ 163 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(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 | @end 180 | -------------------------------------------------------------------------------- /shufflingDemo/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 | 15 | @implementation UIImageView (WebCache) 16 | 17 | - (void)sd_setImageWithURL:(NSURL *)url { 18 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; 19 | } 20 | 21 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 22 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; 23 | } 24 | 25 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 26 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 27 | } 28 | 29 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 30 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; 31 | } 32 | 33 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 34 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; 35 | } 36 | 37 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 38 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; 39 | } 40 | 41 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 42 | [self sd_cancelCurrentImageLoad]; 43 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 44 | 45 | if (!(options & SDWebImageDelayPlaceholder)) { 46 | dispatch_main_async_safe(^{ 47 | self.image = placeholder; 48 | }); 49 | } 50 | 51 | if (url) { 52 | __weak UIImageView *wself = self; 53 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 54 | if (!wself) return; 55 | dispatch_main_sync_safe(^{ 56 | if (!wself) return; 57 | if (image) { 58 | wself.image = image; 59 | [wself setNeedsLayout]; 60 | } else { 61 | if ((options & SDWebImageDelayPlaceholder)) { 62 | wself.image = placeholder; 63 | [wself setNeedsLayout]; 64 | } 65 | } 66 | if (completedBlock && finished) { 67 | completedBlock(image, error, cacheType, url); 68 | } 69 | }); 70 | }]; 71 | [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"]; 72 | } else { 73 | dispatch_main_async_safe(^{ 74 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 75 | if (completedBlock) { 76 | completedBlock(nil, error, SDImageCacheTypeNone, url); 77 | } 78 | }); 79 | } 80 | } 81 | 82 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 83 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; 84 | UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key]; 85 | 86 | [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; 87 | } 88 | 89 | - (NSURL *)sd_imageURL { 90 | return objc_getAssociatedObject(self, &imageURLKey); 91 | } 92 | 93 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { 94 | [self sd_cancelCurrentAnimationImagesLoad]; 95 | __weak UIImageView *wself = self; 96 | 97 | NSMutableArray *operationsArray = [[NSMutableArray alloc] init]; 98 | 99 | for (NSURL *logoImageURL in arrayOfURLs) { 100 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 101 | if (!wself) return; 102 | dispatch_main_sync_safe(^{ 103 | __strong UIImageView *sself = wself; 104 | [sself stopAnimating]; 105 | if (sself && image) { 106 | NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; 107 | if (!currentImages) { 108 | currentImages = [[NSMutableArray alloc] init]; 109 | } 110 | [currentImages addObject:image]; 111 | 112 | sself.animationImages = currentImages; 113 | [sself setNeedsLayout]; 114 | } 115 | [sself startAnimating]; 116 | }); 117 | }]; 118 | [operationsArray addObject:operation]; 119 | } 120 | 121 | [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"]; 122 | } 123 | 124 | - (void)sd_cancelCurrentImageLoad { 125 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"]; 126 | } 127 | 128 | - (void)sd_cancelCurrentAnimationImagesLoad { 129 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; 130 | } 131 | 132 | @end 133 | -------------------------------------------------------------------------------- /shufflingDemo/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 | -------------------------------------------------------------------------------- /shufflingDemo/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 | -------------------------------------------------------------------------------- /shufflingDemo/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // shufflingDemo 4 | // 5 | // Created by 杨鑫 on 2016/11/17. 6 | // Copyright © 2016年 Mr Yang. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /shufflingDemo/favorites-filling-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yangxiniOS/SlidingPositive/05877e53683f165b8dd2ec1cf292f0c3edc14b6a/shufflingDemo/favorites-filling-2.png -------------------------------------------------------------------------------- /shufflingDemo/favorites-filling.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yangxiniOS/SlidingPositive/05877e53683f165b8dd2ec1cf292f0c3edc14b6a/shufflingDemo/favorites-filling.png -------------------------------------------------------------------------------- /shufflingDemo/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // shufflingDemo 4 | // 5 | // Created by 杨鑫 on 2016/11/17. 6 | // Copyright © 2016年 Mr Yang. 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 | -------------------------------------------------------------------------------- /shufflingDemo/演示.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yangxiniOS/SlidingPositive/05877e53683f165b8dd2ec1cf292f0c3edc14b6a/shufflingDemo/演示.gif -------------------------------------------------------------------------------- /shufflingDemoTests/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 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | 24 | 25 | -------------------------------------------------------------------------------- /shufflingDemoTests/shufflingDemoTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // shufflingDemoTests.m 3 | // shufflingDemoTests 4 | // 5 | // Created by 杨鑫 on 2016/11/17. 6 | // Copyright © 2016年 Mr Yang. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface shufflingDemoTests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation shufflingDemoTests 16 | 17 | - (void)setUp { 18 | [super setUp]; 19 | // Put setup code here. This method is called before the invocation of each test method in the class. 20 | } 21 | 22 | - (void)tearDown { 23 | // Put teardown code here. This method is called after the invocation of each test method in the class. 24 | [super tearDown]; 25 | } 26 | 27 | - (void)testExample { 28 | // This is an example of a functional test case. 29 | // Use XCTAssert and related functions to verify your tests produce the correct results. 30 | } 31 | 32 | - (void)testPerformanceExample { 33 | // This is an example of a performance test case. 34 | [self measureBlock:^{ 35 | // Put the code you want to measure the time of here. 36 | }]; 37 | } 38 | 39 | @end 40 | --------------------------------------------------------------------------------