UIImage+MemoryCacheCost.m 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. frameCount = image.images.count > 0 ? image.images.count : 1;
  22. #endif
  23. NSUInteger cost = bytesPerFrame * frameCount;
  24. return cost;
  25. }
  26. @implementation UIImage (MemoryCacheCost)
  27. - (NSUInteger)sd_memoryCost {
  28. NSNumber *value = objc_getAssociatedObject(self, @selector(sd_memoryCost));
  29. NSUInteger memoryCost;
  30. if (value != nil) {
  31. memoryCost = [value unsignedIntegerValue];
  32. } else {
  33. memoryCost = SDMemoryCacheCostForImage(self);
  34. }
  35. return memoryCost;
  36. }
  37. - (void)setSd_memoryCost:(NSUInteger)sd_memoryCost {
  38. objc_setAssociatedObject(self, @selector(sd_memoryCost), @(sd_memoryCost), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  39. }
  40. @end