异步图片下载类 带缓存 继承UIimage
DownloadImgView.h
1 2 3 4 5 6 7 8 9 |
DownloadImgView.h#import <UIKit/UIKit.h> @interface DownloadImgView : UIImageView @property (strong, nonatomic) NSURL *imageURL; @property (strong, nonatomic) UIImage *placeholderImage; @property (nonatomic) CGSize scaleSize; @end |
DownloadImgView.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
#import "DownloadImgView.h" #import "TMCache.h" @implementation DownloadImgView - (void)setImageURL:(NSURL *)url { _imageURL = url; [[TMCache sharedCache] objectForKey:[url absoluteString] block:^(TMCache *cache, NSString *key, id object) { if (object) { [self setImageOnMainThread:(UIImage *)object]; return; } NSLog(@"cache miss, requesting %@", url); NSURLResponse *response = nil; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; UIImage *image = [[UIImage alloc] initWithData:data scale:[[UIScreen mainScreen] scale]]; if (!CGSizeEqualToSize(self.scaleSize,CGSizeZero)) { image = [self reSizeImage:image toSize:CGSizeMake(60, 80)]; } [self setImageOnMainThread:image]; [[TMCache sharedCache] setObject:image forKey:[url absoluteString]]; }]; } - (void)setImageOnMainThread:(UIImage *)image { NSLog(@"setting view image %@", NSStringFromCGSize(image.size)); dispatch_async(dispatch_get_main_queue(), ^{ if (!image) if (_placeholderImage) { self.image = _placeholderImage; }else{ return; } else{ self.image = image; } }); } - (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize { UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height)); [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)]; UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return reSizeImage; } |
使用:
1 2 3 4 5 |
DownloadImgView *imageView = [[DownloadImgView alloc] initWithFrame:CGRectMake(17, 17, 90.0f, 90.0f)]; NSString *imageUrl = "http://www.baidu.com/img/bdlogo.gif" NSURL *requestUrl = [NSURL URLWithString:imageUrl]; imageView.scaleSize = CGSizeMake(60, 80); imageView.imageURL = requestUrl; |
转载请注明:天狐博客 » iOS异步加载网络图片下载类带缓存