我正在使用SDWebImage来加载和缓存我正在加载到tableViewCells中的图像。我想调整图像大小以获得更好的滚动性能,并编写一个调整大小函数作为UIImageView的扩展,它将图像大小调整为其imageView的大小。在寻找解决方案时,我发现SDWebImageManager函数可用于在缓存之前调整Image的大小,唯一的问题是参数是UIImage,所以我无法调整它以适应它所在的ImageView。我希望你伙计们明白了我的意思。这就是我现在正在做的事情,这对性能有点不利,因为每次显示单元格时都会调整大小。 size当然是ImageView的大小。
cell.firstImage.sd_setImage(with: URL(string: image0Uri), completed: { (img, err, cache, url) in
cell.firstImage.resize(toSize: size)
})
答案 0 :(得分:0)
获取后可以调整图像大小。只是通过图像和图像的高度和宽度。
[cell.imgview sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",Image_URL2]] placeholderImage:[UIImage imageNamed:@"imagename"] completed:^(UIImage image, NSError error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image) {
cell.imgview.image=[Utility compressImageDynamic:image hight:(360 [UIScreen mainScreen].bounds.size.width)/320 width:(360 [UIScreen mainScreen].bounds.size.width)/320];
}
else{
}
}];
以下是reSize图像的功能。
-(UIImage )compressImageDynamic:(UIImage )image hight:(float)x width:(float)y{
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float maxHeight = x;
float maxWidth = y;
float imgRatio = actualWidth/actualHeight;
float maxRatio = maxWidth/maxHeight;
float compressionQuality = 1;//50 percent compression
if (actualHeight > maxHeight || actualWidth > maxWidth){
if(imgRatio < maxRatio){
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
}
else if(imgRatio > maxRatio){
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}
else{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}else{
actualHeight = maxHeight;
actualWidth = maxWidth;
compressionQuality = 1;
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
UIGraphicsEndImageContext();
return [UIImage imageWithData:imageData];
}
答案 1 :(得分:0)
这比一行代码要复杂一点,你可能需要手动加载图像,然后调整大小,然后用你自己的密钥保存到缓存中,然后用你的密钥获取下层reso
也许是这样的:
SDImageCache.shared().queryCacheOperation(forKey: "KEY", done: { (image, data, type) in
if let image = image {
self.firstImage.image = image
} else {
if let imgUrl = url {
SDWebImageManager.shared().loadImage(with: URL(string: imgUrl), options: [], progress: nil) { (image, data, error, type, done, url) in
image.resize(toSize: size)
self.firstImage.image = image
SDImageCache.shared().store(image, forKey: "KEY", completion: nil)
})
} else {
self.firstImage.image = UIImage(named: "img_default")
}
}
})