YYImage.m 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. //
  2. // YYImage.m
  3. // YYKit <https://github.com/ibireme/YYKit>
  4. //
  5. // Created by ibireme on 14/10/20.
  6. // Copyright (c) 2015 ibireme.
  7. //
  8. // This source code is licensed under the MIT-style license found in the
  9. // LICENSE file in the root directory of this source tree.
  10. //
  11. #import "YYImage.h"
  12. #import <libkern/OSAtomic.h>
  13. /**
  14. An array of NSNumber objects, shows the best order for path scale search.
  15. e.g. iPhone3GS:@[@1,@2,@3] iPhone5:@[@2,@3,@1] iPhone6 Plus:@[@3,@2,@1]
  16. */
  17. static NSArray *_NSBundlePreferredScales() {
  18. static NSArray *scales;
  19. static dispatch_once_t onceToken;
  20. dispatch_once(&onceToken, ^{
  21. CGFloat screenScale = [UIScreen mainScreen].scale;
  22. if (screenScale <= 1) {
  23. scales = @[@1,@2,@3];
  24. } else if (screenScale <= 2) {
  25. scales = @[@2,@3,@1];
  26. } else {
  27. scales = @[@3,@2,@1];
  28. }
  29. });
  30. return scales;
  31. }
  32. /**
  33. Add scale modifier to the file name (without path extension),
  34. From @"name" to @"name@2x".
  35. e.g.
  36. <table>
  37. <tr><th>Before </th><th>After(scale:2)</th></tr>
  38. <tr><td>"icon" </td><td>"icon@2x" </td></tr>
  39. <tr><td>"icon " </td><td>"icon @2x" </td></tr>
  40. <tr><td>"icon.top" </td><td>"icon.top@2x" </td></tr>
  41. <tr><td>"/p/name" </td><td>"/p/name@2x" </td></tr>
  42. <tr><td>"/path/" </td><td>"/path/" </td></tr>
  43. </table>
  44. @param scale Resource scale.
  45. @return String by add scale modifier, or just return if it's not end with file name.
  46. */
  47. static NSString *_NSStringByAppendingNameScale(NSString *string, CGFloat scale) {
  48. if (!string) return nil;
  49. if (fabs(scale - 1) <= __FLT_EPSILON__ || string.length == 0 || [string hasSuffix:@"/"]) return string.copy;
  50. return [string stringByAppendingFormat:@"@%@x", @(scale)];
  51. }
  52. /**
  53. Return the path scale.
  54. e.g.
  55. <table>
  56. <tr><th>Path </th><th>Scale </th></tr>
  57. <tr><td>"icon.png" </td><td>1 </td></tr>
  58. <tr><td>"icon@2x.png" </td><td>2 </td></tr>
  59. <tr><td>"icon@2.5x.png" </td><td>2.5 </td></tr>
  60. <tr><td>"icon@2x" </td><td>1 </td></tr>
  61. <tr><td>"icon@2x..png" </td><td>1 </td></tr>
  62. <tr><td>"icon@2x.png/" </td><td>1 </td></tr>
  63. </table>
  64. */
  65. static CGFloat _NSStringPathScale(NSString *string) {
  66. if (string.length == 0 || [string hasSuffix:@"/"]) return 1;
  67. NSString *name = string.stringByDeletingPathExtension;
  68. __block CGFloat scale = 1;
  69. NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:@"@[0-9]+\\.?[0-9]*x$" options:NSRegularExpressionAnchorsMatchLines error:nil];
  70. [pattern enumerateMatchesInString:name options:kNilOptions range:NSMakeRange(0, name.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
  71. if (result.range.location >= 3) {
  72. scale = [string substringWithRange:NSMakeRange(result.range.location + 1, result.range.length - 2)].doubleValue;
  73. }
  74. }];
  75. return scale;
  76. }
  77. @implementation YYImage {
  78. YYImageDecoder *_decoder;
  79. NSArray *_preloadedFrames;
  80. OSSpinLock _preloadedLock;
  81. NSUInteger _bytesPerFrame;
  82. }
  83. + (YYImage *)imageNamed:(NSString *)name {
  84. if (name.length == 0) return nil;
  85. if ([name hasSuffix:@"/"]) return nil;
  86. NSString *res = name.stringByDeletingPathExtension;
  87. NSString *ext = name.pathExtension;
  88. NSString *path = nil;
  89. CGFloat scale = 1;
  90. NSArray *scales = _NSBundlePreferredScales();
  91. for (int s = 0; s < scales.count; s++) {
  92. scale = ((NSNumber *)scales[s]).floatValue;
  93. NSString *scaledName = _NSStringByAppendingNameScale(res, scale);
  94. // If no extension, guess by system supported (same as UIImage).
  95. NSArray *exts = ext.length > 0 ? @[ext] : @[@"", @"png", @"jpeg", @"jpg", @"gif", @"webp"];
  96. for (NSString *e in exts) {
  97. path = [[NSBundle mainBundle] pathForResource:scaledName ofType:e];
  98. if (path) break;
  99. }
  100. if (path) break;
  101. }
  102. if (path.length == 0) return nil;
  103. NSData *data = [NSData dataWithContentsOfFile:path];
  104. if (data.length == 0) return nil;
  105. return [[self alloc] initWithData:data scale:scale];
  106. }
  107. + (YYImage *)imageWithContentsOfFile:(NSString *)path {
  108. return [[self alloc] initWithContentsOfFile:path];
  109. }
  110. + (YYImage *)imageWithData:(NSData *)data {
  111. return [[self alloc] initWithData:data];
  112. }
  113. + (YYImage *)imageWithData:(NSData *)data scale:(CGFloat)scale {
  114. return [[self alloc] initWithData:data scale:scale];
  115. }
  116. - (instancetype)initWithContentsOfFile:(NSString *)path {
  117. NSData *data = [NSData dataWithContentsOfFile:path];
  118. return [self initWithData:data scale:_NSStringPathScale(path)];
  119. }
  120. - (instancetype)initWithData:(NSData *)data {
  121. return [self initWithData:data scale:1];
  122. }
  123. - (instancetype)initWithData:(NSData *)data scale:(CGFloat)scale {
  124. if (data.length == 0) return nil;
  125. if (scale <= 0) scale = [UIScreen mainScreen].scale;
  126. _preloadedLock = OS_SPINLOCK_INIT;
  127. @autoreleasepool {
  128. YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:scale];
  129. YYImageFrame *frame = [decoder frameAtIndex:0 decodeForDisplay:YES];
  130. UIImage *image = frame.image;
  131. if (!image) return nil;
  132. self = [self initWithCGImage:image.CGImage scale:decoder.scale orientation:image.imageOrientation];
  133. if (!self) return nil;
  134. _animatedImageType = decoder.type;
  135. if (decoder.frameCount > 1) {
  136. _decoder = decoder;
  137. _bytesPerFrame = CGImageGetBytesPerRow(image.CGImage) * CGImageGetHeight(image.CGImage);
  138. _animatedImageMemorySize = _bytesPerFrame * decoder.frameCount;
  139. }
  140. self.yy_isDecodedForDisplay = YES;
  141. }
  142. return self;
  143. }
  144. - (NSData *)animatedImageData {
  145. return _decoder.data;
  146. }
  147. - (void)setPreloadAllAnimatedImageFrames:(BOOL)preloadAllAnimatedImageFrames {
  148. if (_preloadAllAnimatedImageFrames != preloadAllAnimatedImageFrames) {
  149. if (preloadAllAnimatedImageFrames && _decoder.frameCount > 0) {
  150. NSMutableArray *frames = [NSMutableArray new];
  151. for (NSUInteger i = 0, max = _decoder.frameCount; i < max; i++) {
  152. UIImage *img = [self animatedImageFrameAtIndex:i];
  153. if (img) {
  154. [frames addObject:img];
  155. } else {
  156. [frames addObject:[NSNull null]];
  157. }
  158. }
  159. OSSpinLockLock(&_preloadedLock);
  160. _preloadedFrames = frames;
  161. OSSpinLockUnlock(&_preloadedLock);
  162. } else {
  163. OSSpinLockLock(&_preloadedLock);
  164. _preloadedFrames = nil;
  165. OSSpinLockUnlock(&_preloadedLock);
  166. }
  167. }
  168. }
  169. #pragma mark - protocol NSCoding
  170. - (instancetype)initWithCoder:(NSCoder *)aDecoder {
  171. NSNumber *scale = [aDecoder decodeObjectForKey:@"YYImageScale"];
  172. NSData *data = [aDecoder decodeObjectForKey:@"YYImageData"];
  173. if (data.length) {
  174. self = [self initWithData:data scale:scale.doubleValue];
  175. } else {
  176. self = [super initWithCoder:aDecoder];
  177. }
  178. return self;
  179. }
  180. - (void)encodeWithCoder:(NSCoder *)aCoder {
  181. if (_decoder.data.length) {
  182. [aCoder encodeObject:@(self.scale) forKey:@"YYImageScale"];
  183. [aCoder encodeObject:_decoder.data forKey:@"YYImageData"];
  184. } else {
  185. [super encodeWithCoder:aCoder]; // Apple use UIImagePNGRepresentation() to encode UIImage.
  186. }
  187. }
  188. #pragma mark - protocol YYAnimatedImage
  189. - (NSUInteger)animatedImageFrameCount {
  190. return _decoder.frameCount;
  191. }
  192. - (NSUInteger)animatedImageLoopCount {
  193. return _decoder.loopCount;
  194. }
  195. - (NSUInteger)animatedImageBytesPerFrame {
  196. return _bytesPerFrame;
  197. }
  198. - (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index {
  199. if (index >= _decoder.frameCount) return nil;
  200. OSSpinLockLock(&_preloadedLock);
  201. UIImage *image = _preloadedFrames[index];
  202. OSSpinLockUnlock(&_preloadedLock);
  203. if (image) return image == (id)[NSNull null] ? nil : image;
  204. return [_decoder frameAtIndex:index decodeForDisplay:YES].image;
  205. }
  206. - (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index {
  207. NSTimeInterval duration = [_decoder frameDurationAtIndex:index];
  208. /*
  209. http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp
  210. Many annoying ads specify a 0 duration to make an image flash as quickly as
  211. possible. We follow Safari and Firefox's behavior and use a duration of 100 ms
  212. for any frames that specify a duration of <= 10 ms.
  213. See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information.
  214. See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser.
  215. */
  216. if (duration < 0.011f) return 0.100f;
  217. return duration;
  218. }
  219. @end