我目前正在使用SDWebimage并调用它,不确定它是否是缓存或我如何检查它?另外,如何在不显示拉伸的情况下相应地缩放它。图片原来是512 x 512,我想缩小它。我看到这篇文章不确定我是否应该使用这种方法? Resize UICollectionView cells after image inside has been downloaded
//setting up each cell
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionGridCell *myCell = [collectionView
dequeueReusableCellWithReuseIdentifier:@"GridCell"
forIndexPath:indexPath];
long row = [indexPath row];
NSURL *baseUrl = [NSURL URLWithString:@"http://example.com/"];
NSString *imageItemName = [homeImages objectAtIndex:row];
NSURL *url = [NSURL URLWithString:imageItemName relativeToURL:baseUrl];
// 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 resizeImage:image newSize:CGSizeMake(75,75)];
}];
return myCell;
}
- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGImageRef imageRef = image.CGImage;
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);
CGContextConcatCTM(context, flipVertical);
// Draw into the context; this scales the image
CGContextDrawImage(context, newRect, imageRef);
// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
UIGraphicsEndImageContext();
return newImage;
}
答案 0 :(得分:1)
SDWebImage docs表示会自动缓存。至于扩展,有大量的网络代码like this。诀窍是将其与SDWebImage集成。幸运的是,它提供了一个完成块:
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)];
}];
简单的比例看起来像这样(未经测试):
- (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;
}
顺便提一下,我注意到您使用通用字符串操作来构建URL。你最好在字符串上使用专门的方法,如下所示:
// 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];