如何使用SDWebImage为多个大小的图像缓存图像

时间:2016-04-11 13:36:45

标签: ios image caching sdwebimage

从我的网络服务我得到多个大小的图像。我在TableView中加载它们。当我加载新的图像时,这些图像在占位符和原始图像之间尚未缓存,或者有时图像看起来比通常的尺寸小。但只是向下或向上滚动实际上解决了问题,但我希望它们从一开始就是原始大小。但是,从下次我想,它会以原始形状出现,因为图片已经被缓存了

首先

Initial

稍微滚动

enter image description here

我在cellForRowAtIndexPath中的代码:

[cell.image sd_setImageWithURL:[NSURL URLWithString:[NSMutableString stringWithFormat:@"%@app/media/access/pictures?p=%@",baseurl,data.picPath]]
                 placeholderImage:[UIImage imageNamed: @"image_loader.gif"]];

然后在heightForRowAtIndexPath:

NSURL *filePath = [NSURL URLWithString:[NSMutableString stringWithFormat:@"%@app/media/access/pictures?p=%@",baseurl,data.picPath]];

        NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:filePath];
        UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key];
        self.img = image;



        if (self.img.size.width > CGRectGetWidth(self.view.bounds)) {
            CGFloat ratio = self.img.size.height / self.img.size.width;
            return CGRectGetWidth(self.view.bounds) * ratio+140;
        } else {

            return self.img.size.height+180;
        }

我已经访问了https://github.com/rs/SDWebImage,在他们的常见问题部分他们已经提到过这个问题,但建议的解决方案并不适合我!

1 个答案:

答案 0 :(得分:0)

实际上我做了什么,我检查了图像是否已经缓存,如果没有,我已经在heightForRowAtIndexPath下异步下载了它:

if(image != NULL)
        {
        self.img = image;
        }
        else
        {
            SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
            [downloader downloadImageWithURL:filePath
                                     options:0
                                    progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                                        // progression tracking code
                                    }
                                   completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                                       if (image && finished) {
                                           // do something with image

                                           self.img = image;

                                       }
                                   }];

        }