我正在使用 SDWebImage 下载缩略图。在使用 - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL
委托(delegate)方法缓存它们之前,我调整了它们的大小。
我用来重新调整图像的代码是:
- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize Image:(UIImage *)image
{
UIImage *sourceImage = image;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor > heightFactor) {
scaleFactor = widthFactor; // scale to fit height
} else {
scaleFactor = heightFactor; // scale to fit width
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor > heightFactor) {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
} else {
if (widthFactor < heightFactor) {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
}
UIGraphicsBeginImageContextWithOptions(targetSize, YES, 0); // this will crop
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
起初,我使用了 UIGraphicsBeginImageContext(targetSize);
但是视网膜设备上的图像模糊所以我将函数更改为 UIGraphicsBeginImageContextWithOptions(targetSize, YES, 0);
但现在我的图像在我的 TableView 单元格中显得更大了。似乎调整代码生成了更高清晰度的图像,但 SDWebImage 库不知道如何正确加载它们。
正确大小的图像位于底部,顶部的图像大小不正确。
预先感谢您的帮助
最佳答案
明白了,
您可以通过将图像设置为 UIImage imageWithCGImage:image.CGImage scale:[[UIScreen mainScreen] scale] orientation:image.imageOrientation]; 来指定它正在加载视网膜图像的 UIImageView;
关于ios - SDWebImage 使用 UIGraphicsBeginImageContextWithOptions 调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31291261/