UIImage+MemoryCacheCost.m 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. * This file is part of the SDWebImage package.
  3. * (c) Olivier Poitrey <rs@dailymotion.com>
  4. *
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. */
  8. #import "UIImage+MemoryCacheCost.h"
  9. #import "objc/runtime.h"
  10. #import "NSImage+Compatibility.h"
  11. FOUNDATION_STATIC_INLINE NSUInteger SDMemoryCacheCostForImage(UIImage *image) {
  12. CGImageRef imageRef = image.CGImage;
  13. if (!imageRef) {
  14. return 0;
  15. }
  16. NSUInteger bytesPerFrame = CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef);
  17. NSUInteger frameCount;
  18. #if SD_MAC
  19. frameCount = 1;
  20. #elif SD_UIKIT || SD_WATCH
  21. // Filter the same frame in `_UIAnimatedImage`.
  22. frameCount = image.images.count > 1 ? [NSSet setWithArray:image.images].count : 1;
  23. #endif
  24. NSUInteger cost = bytesPerFrame * frameCount;
  25. return cost;
  26. }
  27. @implementation UIImage (MemoryCacheCost)
  28. - (NSUInteger)sd_memoryCost {
  29. NSNumber *value = objc_getAssociatedObject(self, @selector(sd_memoryCost));
  30. NSUInteger memoryCost;
  31. if (value != nil) {
  32. memoryCost = [value unsignedIntegerValue];
  33. } else {
  34. memoryCost = SDMemoryCacheCostForImage(self);
  35. }
  36. return memoryCost;
  37. }
  38. - (void)setSd_memoryCost:(NSUInteger)sd_memoryCost {
  39. objc_setAssociatedObject(self, @selector(sd_memoryCost), @(sd_memoryCost), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  40. }
  41. @end