XHWebImageAutoSize.m 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // XHWebImageAutoSize.m
  3. // XHWebImageHeightLayoutExample
  4. //
  5. // Created by zhuxiaohui on 2016/11/16.
  6. // Copyright © 2016年 it7090.com. All rights reserved.
  7. // https://github.com/CoderZhuXH/XHWebImageAutoSize
  8. #import "XHWebImageAutoSize.h"
  9. static CGFloat const estimateDefaultHeight = 100;
  10. static CGFloat const estimateDefaultWidth = 90;
  11. @implementation XHWebImageAutoSize
  12. +(CGFloat)imageHeightForURL:(NSURL *)url layoutWidth:(CGFloat)layoutWidth estimateHeight:(CGFloat )estimateHeight{
  13. CGFloat showHeight = estimateDefaultHeight;
  14. if(estimateHeight) showHeight = estimateHeight;
  15. if(!url || !layoutWidth) return showHeight;
  16. CGSize size = [self imageSizeFromCacheForURL:url];
  17. CGFloat imgWidth = size.width;
  18. CGFloat imgHeight = size.height;
  19. if(imgWidth>0 && imgHeight >0){
  20. showHeight = layoutWidth/imgWidth*imgHeight;
  21. }
  22. return showHeight;
  23. }
  24. +(CGFloat)imageWidthForURL:(NSURL *)url layoutHeight:(CGFloat)layoutHeight estimateWidth:(CGFloat )estimateWidth{
  25. CGFloat showWidth = estimateDefaultWidth;
  26. if(estimateWidth) showWidth = estimateWidth;
  27. if(!url || !layoutHeight) return showWidth;
  28. CGSize size = [self imageSizeFromCacheForURL:url];
  29. CGFloat imgWidth = size.width;
  30. CGFloat imgHeight = size.height;
  31. if(imgWidth>0 && imgHeight >0){
  32. showWidth = layoutHeight/imgHeight*imgWidth;
  33. }
  34. return showWidth;
  35. }
  36. +(void)storeImageSize:(UIImage *)image forURL:(NSURL *)url completed:(nullable XHWebImageAutoSizeCacheCompletionBlock)completedBlock{
  37. [[XHWebImageAutoSizeCache shardCache] storeImageSize:image forKey:[self cacheKeyForURL:url] completed:completedBlock];
  38. }
  39. +(void)storeReloadState:(BOOL)state forURL:(NSURL *)url completed:(nullable XHWebImageAutoSizeCacheCompletionBlock)completedBlock{
  40. [[XHWebImageAutoSizeCache shardCache] storeReloadState:state forKey:[self cacheKeyForURL:url] completed:completedBlock];
  41. }
  42. +(CGSize )imageSizeFromCacheForURL:(NSURL *)url{
  43. return [[XHWebImageAutoSizeCache shardCache] imageSizeFromCacheForKey:[self cacheKeyForURL:url]];
  44. }
  45. +(BOOL)reloadStateFromCacheForURL:(NSURL *)url{
  46. return [[XHWebImageAutoSizeCache shardCache] reloadStateFromCacheForKey:[self cacheKeyForURL:url]];
  47. }
  48. #pragma mark - XHWebImageAutoSize (private)
  49. +(NSString *)cacheKeyForURL:(NSURL *)url{
  50. return [url absoluteString];
  51. }
  52. @end