YYAnimatedImageView.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. //
  2. // YYAnimatedImageView.m
  3. // YYImage <https://github.com/ibireme/YYImage>
  4. //
  5. // Created by ibireme on 14/10/19.
  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 "YYAnimatedImageView.h"
  12. #import "YYImageCoder.h"
  13. #import <pthread.h>
  14. #import <mach/mach.h>
  15. #define BUFFER_SIZE (10 * 1024 * 1024) // 10MB (minimum memory buffer size)
  16. #define LOCK(...) dispatch_semaphore_wait(self->_lock, DISPATCH_TIME_FOREVER); \
  17. __VA_ARGS__; \
  18. dispatch_semaphore_signal(self->_lock);
  19. #define LOCK_VIEW(...) dispatch_semaphore_wait(view->_lock, DISPATCH_TIME_FOREVER); \
  20. __VA_ARGS__; \
  21. dispatch_semaphore_signal(view->_lock);
  22. static int64_t _YYDeviceMemoryTotal() {
  23. int64_t mem = [[NSProcessInfo processInfo] physicalMemory];
  24. if (mem < -1) mem = -1;
  25. return mem;
  26. }
  27. static int64_t _YYDeviceMemoryFree() {
  28. mach_port_t host_port = mach_host_self();
  29. mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
  30. vm_size_t page_size;
  31. vm_statistics_data_t vm_stat;
  32. kern_return_t kern;
  33. kern = host_page_size(host_port, &page_size);
  34. if (kern != KERN_SUCCESS) return -1;
  35. kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
  36. if (kern != KERN_SUCCESS) return -1;
  37. return vm_stat.free_count * page_size;
  38. }
  39. /**
  40. A proxy used to hold a weak object.
  41. It can be used to avoid retain cycles, such as the target in NSTimer or CADisplayLink.
  42. */
  43. @interface _YYImageWeakProxy : NSProxy
  44. @property (nonatomic, weak, readonly) id target;
  45. - (instancetype)initWithTarget:(id)target;
  46. + (instancetype)proxyWithTarget:(id)target;
  47. @end
  48. @implementation _YYImageWeakProxy
  49. - (instancetype)initWithTarget:(id)target {
  50. _target = target;
  51. return self;
  52. }
  53. + (instancetype)proxyWithTarget:(id)target {
  54. return [[_YYImageWeakProxy alloc] initWithTarget:target];
  55. }
  56. - (id)forwardingTargetForSelector:(SEL)selector {
  57. return _target;
  58. }
  59. - (void)forwardInvocation:(NSInvocation *)invocation {
  60. void *null = NULL;
  61. [invocation setReturnValue:&null];
  62. }
  63. - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
  64. return [NSObject instanceMethodSignatureForSelector:@selector(init)];
  65. }
  66. - (BOOL)respondsToSelector:(SEL)aSelector {
  67. return [_target respondsToSelector:aSelector];
  68. }
  69. - (BOOL)isEqual:(id)object {
  70. return [_target isEqual:object];
  71. }
  72. - (NSUInteger)hash {
  73. return [_target hash];
  74. }
  75. - (Class)superclass {
  76. return [_target superclass];
  77. }
  78. - (Class)class {
  79. return [_target class];
  80. }
  81. - (BOOL)isKindOfClass:(Class)aClass {
  82. return [_target isKindOfClass:aClass];
  83. }
  84. - (BOOL)isMemberOfClass:(Class)aClass {
  85. return [_target isMemberOfClass:aClass];
  86. }
  87. - (BOOL)conformsToProtocol:(Protocol *)aProtocol {
  88. return [_target conformsToProtocol:aProtocol];
  89. }
  90. - (BOOL)isProxy {
  91. return YES;
  92. }
  93. - (NSString *)description {
  94. return [_target description];
  95. }
  96. - (NSString *)debugDescription {
  97. return [_target debugDescription];
  98. }
  99. @end
  100. typedef NS_ENUM(NSUInteger, YYAnimatedImageType) {
  101. YYAnimatedImageTypeNone = 0,
  102. YYAnimatedImageTypeImage,
  103. YYAnimatedImageTypeHighlightedImage,
  104. YYAnimatedImageTypeImages,
  105. YYAnimatedImageTypeHighlightedImages,
  106. };
  107. @interface YYAnimatedImageView() {
  108. @package
  109. UIImage <YYAnimatedImage> *_curAnimatedImage;
  110. dispatch_once_t _onceToken;
  111. dispatch_semaphore_t _lock; ///< lock for _buffer
  112. NSOperationQueue *_requestQueue; ///< image request queue, serial
  113. CADisplayLink *_link; ///< ticker for change frame
  114. NSTimeInterval _time; ///< time after last frame
  115. UIImage *_curFrame; ///< current frame to display
  116. NSUInteger _curIndex; ///< current frame index (from 0)
  117. NSUInteger _totalFrameCount; ///< total frame count
  118. BOOL _loopEnd; ///< weather the loop is end.
  119. NSUInteger _curLoop; ///< current loop count (from 0)
  120. NSUInteger _totalLoop; ///< total loop count, 0 means infinity
  121. NSMutableDictionary *_buffer; ///< frame buffer
  122. BOOL _bufferMiss; ///< whether miss frame on last opportunity
  123. NSUInteger _maxBufferCount; ///< maximum buffer count
  124. NSInteger _incrBufferCount; ///< current allowed buffer count (will increase by step)
  125. CGRect _curContentsRect;
  126. BOOL _curImageHasContentsRect; ///< image has implementated "animatedImageContentsRectAtIndex:"
  127. }
  128. @property (nonatomic, readwrite) BOOL currentIsPlayingAnimation;
  129. - (void)calcMaxBufferCount;
  130. @end
  131. /// An operation for image fetch
  132. @interface _YYAnimatedImageViewFetchOperation : NSOperation
  133. @property (nonatomic, weak) YYAnimatedImageView *view;
  134. @property (nonatomic, assign) NSUInteger nextIndex;
  135. @property (nonatomic, strong) UIImage <YYAnimatedImage> *curImage;
  136. @end
  137. @implementation _YYAnimatedImageViewFetchOperation
  138. - (void)main {
  139. __strong YYAnimatedImageView *view = _view;
  140. if (!view) return;
  141. if ([self isCancelled]) return;
  142. view->_incrBufferCount++;
  143. if (view->_incrBufferCount == 0) [view calcMaxBufferCount];
  144. if ((int)view->_incrBufferCount > (int)view->_maxBufferCount) {
  145. view->_incrBufferCount = view->_maxBufferCount;
  146. }
  147. NSUInteger idx = _nextIndex;
  148. NSUInteger max = view->_incrBufferCount < 1 ? 1 : view->_incrBufferCount;
  149. NSUInteger total = view->_totalFrameCount;
  150. for (int i = 0; i < max; i++, idx++) {
  151. @autoreleasepool {
  152. if (idx >= total) idx = 0;
  153. if ([self isCancelled]) break;
  154. LOCK_VIEW(BOOL miss = (view->_buffer[@(idx)] == nil));
  155. if (miss) {
  156. UIImage *img = [_curImage animatedImageFrameAtIndex:idx];
  157. img = [img yy_imageByDecoded];
  158. if ([self isCancelled]) break;
  159. LOCK_VIEW(view->_buffer[@(idx)] = img ? img : [NSNull null]);
  160. }
  161. }
  162. }
  163. }
  164. @end
  165. @implementation YYAnimatedImageView
  166. - (instancetype)init {
  167. self = [super init];
  168. _runloopMode = NSRunLoopCommonModes;
  169. _autoPlayAnimatedImage = YES;
  170. return self;
  171. }
  172. - (instancetype)initWithFrame:(CGRect)frame {
  173. self = [super initWithFrame:frame];
  174. _runloopMode = NSRunLoopCommonModes;
  175. _autoPlayAnimatedImage = YES;
  176. return self;
  177. }
  178. - (instancetype)initWithImage:(UIImage *)image {
  179. self = [super init];
  180. _runloopMode = NSRunLoopCommonModes;
  181. _autoPlayAnimatedImage = YES;
  182. self.frame = (CGRect) {CGPointZero, image.size };
  183. self.image = image;
  184. return self;
  185. }
  186. - (instancetype)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage {
  187. self = [super init];
  188. _runloopMode = NSRunLoopCommonModes;
  189. _autoPlayAnimatedImage = YES;
  190. CGSize size = image ? image.size : highlightedImage.size;
  191. self.frame = (CGRect) {CGPointZero, size };
  192. self.image = image;
  193. self.highlightedImage = highlightedImage;
  194. return self;
  195. }
  196. // init the animated params.
  197. - (void)resetAnimated {
  198. dispatch_once(&_onceToken, ^{
  199. _lock = dispatch_semaphore_create(1);
  200. _buffer = [NSMutableDictionary new];
  201. _requestQueue = [[NSOperationQueue alloc] init];
  202. _requestQueue.maxConcurrentOperationCount = 1;
  203. _link = [CADisplayLink displayLinkWithTarget:[_YYImageWeakProxy proxyWithTarget:self] selector:@selector(step:)];
  204. if (_runloopMode) {
  205. [_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:_runloopMode];
  206. }
  207. _link.paused = YES;
  208. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
  209. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
  210. });
  211. [_requestQueue cancelAllOperations];
  212. LOCK(
  213. if (_buffer.count) {
  214. NSMutableDictionary *holder = _buffer;
  215. _buffer = [NSMutableDictionary new];
  216. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  217. // Capture the dictionary to global queue,
  218. // release these images in background to avoid blocking UI thread.
  219. [holder class];
  220. });
  221. }
  222. );
  223. _link.paused = YES;
  224. _time = 0;
  225. if (_curIndex != 0) {
  226. [self willChangeValueForKey:@"currentAnimatedImageIndex"];
  227. _curIndex = 0;
  228. [self didChangeValueForKey:@"currentAnimatedImageIndex"];
  229. }
  230. _curAnimatedImage = nil;
  231. _curFrame = nil;
  232. _curLoop = 0;
  233. _totalLoop = 0;
  234. _totalFrameCount = 1;
  235. _loopEnd = NO;
  236. _bufferMiss = NO;
  237. _incrBufferCount = 0;
  238. }
  239. - (void)setImage:(UIImage *)image {
  240. if (self.image == image) return;
  241. [self setImage:image withType:YYAnimatedImageTypeImage];
  242. }
  243. - (void)setHighlightedImage:(UIImage *)highlightedImage {
  244. if (self.highlightedImage == highlightedImage) return;
  245. [self setImage:highlightedImage withType:YYAnimatedImageTypeHighlightedImage];
  246. }
  247. - (void)setAnimationImages:(NSArray *)animationImages {
  248. if (self.animationImages == animationImages) return;
  249. [self setImage:animationImages withType:YYAnimatedImageTypeImages];
  250. }
  251. - (void)setHighlightedAnimationImages:(NSArray *)highlightedAnimationImages {
  252. if (self.highlightedAnimationImages == highlightedAnimationImages) return;
  253. [self setImage:highlightedAnimationImages withType:YYAnimatedImageTypeHighlightedImages];
  254. }
  255. - (void)setHighlighted:(BOOL)highlighted {
  256. [super setHighlighted:highlighted];
  257. if (_link) [self resetAnimated];
  258. [self imageChanged];
  259. }
  260. - (id)imageForType:(YYAnimatedImageType)type {
  261. switch (type) {
  262. case YYAnimatedImageTypeNone: return nil;
  263. case YYAnimatedImageTypeImage: return self.image;
  264. case YYAnimatedImageTypeHighlightedImage: return self.highlightedImage;
  265. case YYAnimatedImageTypeImages: return self.animationImages;
  266. case YYAnimatedImageTypeHighlightedImages: return self.highlightedAnimationImages;
  267. }
  268. return nil;
  269. }
  270. - (YYAnimatedImageType)currentImageType {
  271. YYAnimatedImageType curType = YYAnimatedImageTypeNone;
  272. if (self.highlighted) {
  273. if (self.highlightedAnimationImages.count) curType = YYAnimatedImageTypeHighlightedImages;
  274. else if (self.highlightedImage) curType = YYAnimatedImageTypeHighlightedImage;
  275. }
  276. if (curType == YYAnimatedImageTypeNone) {
  277. if (self.animationImages.count) curType = YYAnimatedImageTypeImages;
  278. else if (self.image) curType = YYAnimatedImageTypeImage;
  279. }
  280. return curType;
  281. }
  282. - (void)setImage:(id)image withType:(YYAnimatedImageType)type {
  283. [self stopAnimating];
  284. if (_link) [self resetAnimated];
  285. _curFrame = nil;
  286. switch (type) {
  287. case YYAnimatedImageTypeNone: break;
  288. case YYAnimatedImageTypeImage: super.image = image; break;
  289. case YYAnimatedImageTypeHighlightedImage: super.highlightedImage = image; break;
  290. case YYAnimatedImageTypeImages: super.animationImages = image; break;
  291. case YYAnimatedImageTypeHighlightedImages: super.highlightedAnimationImages = image; break;
  292. }
  293. [self imageChanged];
  294. }
  295. - (void)imageChanged {
  296. YYAnimatedImageType newType = [self currentImageType];
  297. id newVisibleImage = [self imageForType:newType];
  298. NSUInteger newImageFrameCount = 0;
  299. BOOL hasContentsRect = NO;
  300. if ([newVisibleImage isKindOfClass:[UIImage class]] &&
  301. [newVisibleImage conformsToProtocol:@protocol(YYAnimatedImage)]) {
  302. newImageFrameCount = ((UIImage<YYAnimatedImage> *) newVisibleImage).animatedImageFrameCount;
  303. if (newImageFrameCount > 1) {
  304. hasContentsRect = [((UIImage<YYAnimatedImage> *) newVisibleImage) respondsToSelector:@selector(animatedImageContentsRectAtIndex:)];
  305. }
  306. }
  307. if (!hasContentsRect && _curImageHasContentsRect) {
  308. if (!CGRectEqualToRect(self.layer.contentsRect, CGRectMake(0, 0, 1, 1)) ) {
  309. [CATransaction begin];
  310. [CATransaction setDisableActions:YES];
  311. self.layer.contentsRect = CGRectMake(0, 0, 1, 1);
  312. [CATransaction commit];
  313. }
  314. }
  315. _curImageHasContentsRect = hasContentsRect;
  316. if (hasContentsRect) {
  317. CGRect rect = [((UIImage<YYAnimatedImage> *) newVisibleImage) animatedImageContentsRectAtIndex:0];
  318. [self setContentsRect:rect forImage:newVisibleImage];
  319. }
  320. if (newImageFrameCount > 1) {
  321. [self resetAnimated];
  322. _curAnimatedImage = newVisibleImage;
  323. _curFrame = newVisibleImage;
  324. _totalLoop = _curAnimatedImage.animatedImageLoopCount;
  325. _totalFrameCount = _curAnimatedImage.animatedImageFrameCount;
  326. [self calcMaxBufferCount];
  327. }
  328. [self setNeedsDisplay];
  329. [self didMoved];
  330. }
  331. // dynamically adjust buffer size for current memory.
  332. - (void)calcMaxBufferCount {
  333. NSUInteger bytes = _curAnimatedImage.animatedImageBytesPerFrame;
  334. if (bytes == 0) bytes = 1;
  335. int64_t total = _YYDeviceMemoryTotal();
  336. int64_t free = _YYDeviceMemoryFree();
  337. int64_t max = MIN(total * 0.2, free * 0.6);
  338. max = MAX(max, BUFFER_SIZE);
  339. if (_maxBufferSize) max = max > _maxBufferSize ? _maxBufferSize : max;
  340. _maxBufferCount = (float)max / (float)bytes;
  341. if (_maxBufferCount == 0) _maxBufferCount = 1;
  342. }
  343. - (void)dealloc {
  344. [_requestQueue cancelAllOperations];
  345. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
  346. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
  347. [_link invalidate];
  348. }
  349. - (BOOL)isAnimating {
  350. return self.currentIsPlayingAnimation;
  351. }
  352. - (void)stopAnimating {
  353. [super stopAnimating];
  354. _link.paused = YES;
  355. self.currentIsPlayingAnimation = NO;
  356. }
  357. - (void)startAnimating {
  358. YYAnimatedImageType type = [self currentImageType];
  359. if (type == YYAnimatedImageTypeImages || type == YYAnimatedImageTypeHighlightedImages) {
  360. NSArray *images = [self imageForType:type];
  361. if (images.count > 0) {
  362. [super startAnimating];
  363. self.currentIsPlayingAnimation = YES;
  364. }
  365. } else {
  366. if (_curAnimatedImage && _link.paused) {
  367. _curLoop = 0;
  368. _loopEnd = NO;
  369. _link.paused = NO;
  370. self.currentIsPlayingAnimation = YES;
  371. }
  372. }
  373. }
  374. - (void)didReceiveMemoryWarning:(NSNotification *)notification {
  375. [_requestQueue cancelAllOperations];
  376. [_requestQueue addOperationWithBlock: ^{
  377. _incrBufferCount = -60 - (int)(arc4random() % 120); // about 1~3 seconds to grow back..
  378. NSNumber *next = @((_curIndex + 1) % _totalFrameCount);
  379. LOCK(
  380. NSArray * keys = _buffer.allKeys;
  381. for (NSNumber * key in keys) {
  382. if (![key isEqualToNumber:next]) { // keep the next frame for smoothly animation
  383. [_buffer removeObjectForKey:key];
  384. }
  385. }
  386. )//LOCK
  387. }];
  388. }
  389. - (void)didEnterBackground:(NSNotification *)notification {
  390. [_requestQueue cancelAllOperations];
  391. NSNumber *next = @((_curIndex + 1) % _totalFrameCount);
  392. LOCK(
  393. NSArray * keys = _buffer.allKeys;
  394. for (NSNumber * key in keys) {
  395. if (![key isEqualToNumber:next]) { // keep the next frame for smoothly animation
  396. [_buffer removeObjectForKey:key];
  397. }
  398. }
  399. )//LOCK
  400. }
  401. - (void)step:(CADisplayLink *)link {
  402. UIImage <YYAnimatedImage> *image = _curAnimatedImage;
  403. NSMutableDictionary *buffer = _buffer;
  404. UIImage *bufferedImage = nil;
  405. NSUInteger nextIndex = (_curIndex + 1) % _totalFrameCount;
  406. BOOL bufferIsFull = NO;
  407. if (!image) return;
  408. if (_loopEnd) { // view will keep in last frame
  409. [self stopAnimating];
  410. return;
  411. }
  412. NSTimeInterval delay = 0;
  413. if (!_bufferMiss) {
  414. _time += link.duration;
  415. delay = [image animatedImageDurationAtIndex:_curIndex];
  416. if (_time < delay) return;
  417. _time -= delay;
  418. if (nextIndex == 0) {
  419. _curLoop++;
  420. if (_curLoop >= _totalLoop && _totalLoop != 0) {
  421. _loopEnd = YES;
  422. [self stopAnimating];
  423. [self.layer setNeedsDisplay]; // let system call `displayLayer:` before runloop sleep
  424. return; // stop at last frame
  425. }
  426. }
  427. delay = [image animatedImageDurationAtIndex:nextIndex];
  428. if (_time > delay) _time = delay; // do not jump over frame
  429. }
  430. LOCK(
  431. bufferedImage = buffer[@(nextIndex)];
  432. if (bufferedImage) {
  433. if ((int)_incrBufferCount < _totalFrameCount) {
  434. [buffer removeObjectForKey:@(nextIndex)];
  435. }
  436. [self willChangeValueForKey:@"currentAnimatedImageIndex"];
  437. _curIndex = nextIndex;
  438. [self didChangeValueForKey:@"currentAnimatedImageIndex"];
  439. _curFrame = bufferedImage == (id)[NSNull null] ? nil : bufferedImage;
  440. if (_curImageHasContentsRect) {
  441. _curContentsRect = [image animatedImageContentsRectAtIndex:_curIndex];
  442. [self setContentsRect:_curContentsRect forImage:_curFrame];
  443. }
  444. nextIndex = (_curIndex + 1) % _totalFrameCount;
  445. _bufferMiss = NO;
  446. if (buffer.count == _totalFrameCount) {
  447. bufferIsFull = YES;
  448. }
  449. } else {
  450. _bufferMiss = YES;
  451. }
  452. )//LOCK
  453. if (!_bufferMiss) {
  454. [self.layer setNeedsDisplay]; // let system call `displayLayer:` before runloop sleep
  455. }
  456. if (!bufferIsFull && _requestQueue.operationCount == 0) { // if some work not finished, wait for next opportunity
  457. _YYAnimatedImageViewFetchOperation *operation = [_YYAnimatedImageViewFetchOperation new];
  458. operation.view = self;
  459. operation.nextIndex = nextIndex;
  460. operation.curImage = image;
  461. [_requestQueue addOperation:operation];
  462. }
  463. }
  464. - (void)displayLayer:(CALayer *)layer {
  465. if (_curFrame) {
  466. layer.contents = (__bridge id)_curFrame.CGImage;
  467. }
  468. }
  469. - (void)setContentsRect:(CGRect)rect forImage:(UIImage *)image{
  470. CGRect layerRect = CGRectMake(0, 0, 1, 1);
  471. if (image) {
  472. CGSize imageSize = image.size;
  473. if (imageSize.width > 0.01 && imageSize.height > 0.01) {
  474. layerRect.origin.x = rect.origin.x / imageSize.width;
  475. layerRect.origin.y = rect.origin.y / imageSize.height;
  476. layerRect.size.width = rect.size.width / imageSize.width;
  477. layerRect.size.height = rect.size.height / imageSize.height;
  478. layerRect = CGRectIntersection(layerRect, CGRectMake(0, 0, 1, 1));
  479. if (CGRectIsNull(layerRect) || CGRectIsEmpty(layerRect)) {
  480. layerRect = CGRectMake(0, 0, 1, 1);
  481. }
  482. }
  483. }
  484. [CATransaction begin];
  485. [CATransaction setDisableActions:YES];
  486. self.layer.contentsRect = layerRect;
  487. [CATransaction commit];
  488. }
  489. - (void)didMoved {
  490. if (self.autoPlayAnimatedImage) {
  491. if(self.superview && self.window) {
  492. [self startAnimating];
  493. } else {
  494. [self stopAnimating];
  495. }
  496. }
  497. }
  498. - (void)didMoveToWindow {
  499. [super didMoveToWindow];
  500. [self didMoved];
  501. }
  502. - (void)didMoveToSuperview {
  503. [super didMoveToSuperview];
  504. [self didMoved];
  505. }
  506. - (void)setCurrentAnimatedImageIndex:(NSUInteger)currentAnimatedImageIndex {
  507. if (!_curAnimatedImage) return;
  508. if (currentAnimatedImageIndex >= _curAnimatedImage.animatedImageFrameCount) return;
  509. if (_curIndex == currentAnimatedImageIndex) return;
  510. void (^block)() = ^{
  511. LOCK(
  512. [_requestQueue cancelAllOperations];
  513. [_buffer removeAllObjects];
  514. [self willChangeValueForKey:@"currentAnimatedImageIndex"];
  515. _curIndex = currentAnimatedImageIndex;
  516. [self didChangeValueForKey:@"currentAnimatedImageIndex"];
  517. _curFrame = [_curAnimatedImage animatedImageFrameAtIndex:_curIndex];
  518. if (_curImageHasContentsRect) {
  519. _curContentsRect = [_curAnimatedImage animatedImageContentsRectAtIndex:_curIndex];
  520. }
  521. _time = 0;
  522. _loopEnd = NO;
  523. _bufferMiss = NO;
  524. [self.layer setNeedsDisplay];
  525. )//LOCK
  526. };
  527. if (pthread_main_np()) {
  528. block();
  529. } else {
  530. dispatch_async(dispatch_get_main_queue(), block);
  531. }
  532. }
  533. - (NSUInteger)currentAnimatedImageIndex {
  534. return _curIndex;
  535. }
  536. - (void)setRunloopMode:(NSString *)runloopMode {
  537. if ([_runloopMode isEqual:runloopMode]) return;
  538. if (_link) {
  539. if (_runloopMode) {
  540. [_link removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:_runloopMode];
  541. }
  542. if (runloopMode.length) {
  543. [_link addToRunLoop:[NSRunLoop mainRunLoop] forMode:runloopMode];
  544. }
  545. }
  546. _runloopMode = runloopMode.copy;
  547. }
  548. #pragma mark - Overrice NSObject(NSKeyValueObservingCustomization)
  549. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  550. if ([key isEqualToString:@"currentAnimatedImageIndex"]) {
  551. return NO;
  552. }
  553. return [super automaticallyNotifiesObserversForKey:key];
  554. }
  555. #pragma mark - NSCoding
  556. - (instancetype)initWithCoder:(NSCoder *)aDecoder {
  557. self = [super initWithCoder:aDecoder];
  558. _runloopMode = [aDecoder decodeObjectForKey:@"runloopMode"];
  559. if (_runloopMode.length == 0) _runloopMode = NSRunLoopCommonModes;
  560. if ([aDecoder containsValueForKey:@"autoPlayAnimatedImage"]) {
  561. _autoPlayAnimatedImage = [aDecoder decodeBoolForKey:@"autoPlayAnimatedImage"];
  562. } else {
  563. _autoPlayAnimatedImage = YES;
  564. }
  565. UIImage *image = [aDecoder decodeObjectForKey:@"YYAnimatedImage"];
  566. UIImage *highlightedImage = [aDecoder decodeObjectForKey:@"YYHighlightedAnimatedImage"];
  567. if (image) {
  568. self.image = image;
  569. [self setImage:image withType:YYAnimatedImageTypeImage];
  570. }
  571. if (highlightedImage) {
  572. self.highlightedImage = highlightedImage;
  573. [self setImage:highlightedImage withType:YYAnimatedImageTypeHighlightedImage];
  574. }
  575. return self;
  576. }
  577. - (void)encodeWithCoder:(NSCoder *)aCoder {
  578. [super encodeWithCoder:aCoder];
  579. [aCoder encodeObject:_runloopMode forKey:@"runloopMode"];
  580. [aCoder encodeBool:_autoPlayAnimatedImage forKey:@"autoPlayAnimatedImage"];
  581. BOOL ani, multi;
  582. ani = [self.image conformsToProtocol:@protocol(YYAnimatedImage)];
  583. multi = (ani && ((UIImage <YYAnimatedImage> *)self.image).animatedImageFrameCount > 1);
  584. if (multi) [aCoder encodeObject:self.image forKey:@"YYAnimatedImage"];
  585. ani = [self.highlightedImage conformsToProtocol:@protocol(YYAnimatedImage)];
  586. multi = (ani && ((UIImage <YYAnimatedImage> *)self.highlightedImage).animatedImageFrameCount > 1);
  587. if (multi) [aCoder encodeObject:self.highlightedImage forKey:@"YYHighlightedAnimatedImage"];
  588. }
  589. @end