How to cache image and scale it correctly?

半世苍凉 提交于 2019-11-29 17:34:12

SDWebImage docs says it caches automatically. As for scaling, there's plenty of net code like this around. The trick is integrating it with SDWebImage. Fortunately, it provides a completion block:

NSURL *url = /* prepare a url... see note below */
[myCell.homeImage setImageWithURL:url
               placeholderImage:[UIImage imageNamed:@"menuButton.png"]
                      completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
    // inspect cacheType here to make sure it's cached as you want it
    myCell.homeImage.image = [self scaleImage:image toSize:CGSizeMake(75,75)];
}];

A simple scale would look something like this (not tested):

- (UIImage *)scale:(UIImage *)image toSize:(CGSize)size {
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

Incidentally, I notice that you use generic string manipulation to build the URL. You'd be better off using the specialized methods on string as follows:

// this can be defined outside cellForRowAtIndexPath
NSURL *baseUrl = [NSURL urlWithString:@"http://example.com/"];

NSString *imageItemName = [homeImages objectAtIndex:row];
NSURL *url = [NSURL URLWithString:imageItemName relativeToURL:baseURL];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!