为不维护方面的 UICollectionview 创建缩略图

Creating thumbnails for UICollectionview not maintaining aspect

我正在为集合视图中的单元格创建缩略图,但一些图像没有保持它们的纵横比。它们看起来被拉伸了,即图像看起来更短更胖。奇怪的是,在我的应用程序中用相机拍摄的图像并没有发生这种情况。它只发生在任何导入的图像上,例如从照片库(即使它们是用相机拍摄的)和我从网络导入的几张图像。单元格图像视图的内容模式设置为 UIViewContentModeScaleAspectFit。我还使用 SDWebImage 进行缓存。

谁能告诉我如何确保所有图像的宽高比保持不变?这是我正在使用的代码...

 - (UIImage *)imageByScalingToSize:(CGSize)size
{
    UIGraphicsBeginImageContextWithOptions(size, YES, 0.0);
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resizedImage;
}

cellForItemAtIndexPath 中的代码...

if ([self.allCacheKeys count] > 0) {
    // check to see if the cacheKeys arrays contains any keys (URLs)
    NSString *cacheKey = self.allCacheKeys[indexPath.row];
    if (cacheKey) {
        [self.imageCache queryDiskCacheForKey:cacheKey done:^(UIImage *image, SDImageCacheType cacheType) {
            if (image) {
                // image is found in the cache
                NSLog(@"Image found in cache!");
                UIImage *thumbnail = [image imageByScalingToSize:CGSizeMake(ITEM_SIZE, ITEM_SIZE)];
                cell.imageView.image = thumbnail;
            }
        }
    }
}

检查以下代码以保持您从网络下载的图像的纵横比。

+(UIImage*)imageWithImage: (UIImage*) sourceImage scaledToWidth: (float) i_width
{
    float oldWidth = sourceImage.size.width;
    float scaleFactor = i_width / oldWidth;

    float newHeight = sourceImage.size.height * scaleFactor;
    float newWidth = oldWidth * scaleFactor;

    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

或以下代码也做同样的事情:

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}