异步图片下载类 带缓存 继承UIimage
DownloadImgView.h
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
#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;
}
使用:
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异步加载网络图片下载类带缓存