你可以在保持规模的同时在iOS上调整UIImage的大小吗?用于缩略图生成

时间:2012-06-20 09:05:48

标签: objective-c ios ios5 uiimage image-scaling

我的应用处理从相机拍摄的图像。我希望能够将这些图像的大小调整为缩略图大小,以便我可以在桌面视图的单元格中显示它们。

“动态”调整大小似乎相当慢,因此我计划在用户将其导入应用程序时调整它们的大小,并将完整大小和缩略图存储在我的业务对象上,使用缩略图等表格视图

这是我用于生成缩略图的代码:

#import "ImageUtils.h"

@implementation ImageUtils

+(UIImage*) generateThumbnailFromImage:(UIImage*)theImage
{
    UIImage * thumbnail;
    CGSize destinationSize = CGSizeMake(100,100);

    UIGraphicsBeginImageContext(destinationSize);
    [theImage drawInRect:CGRectMake(0,0,destinationSize.width, destinationSize.height)];
    thumbnail = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return thumbnail;
}

@end

虽然这似乎可以正确调整图像大小,并大大提高了我的表格的响应性,但图像的缩放是关闭的。

以上将创建100 * 100的UIImage,如何强制它使用AspectFit或AspectFill方法?

我的桌面单元格上的UIImageView是100 * 100,所以我需要调整图像的大小以适应它,而不会扭曲它。

任何指针都会很棒!

2 个答案:

答案 0 :(得分:3)

我意识到这是一个旧线程,但如果你偶然发现这个问题,iOS6中现在有一个更简单的方法。在Apple的文档中找到以下内容之前,我花了很多时间尝试使用此解决方案。

使用:

+ (UIImage *)imageWithCGImage:(CGImageRef)imageRef 
scale:(CGFloat)scale
orientation:(UIImageOrientation)orientation

+ (UIImage *)imageWithCIImage:(CIImage *)ciImage
scale:(CGFloat)scale
orientation:(UIImageOrientation)orientation

如果您想使用它来从名为“image”的UIImage制作缩略图,您可以使用一行代码:

UIImage *thumbnail = [UIImage imageWithCGImage:image.cgImage
scale:someScale
orientation:image.imageOrientation];

我发现大于1的数字会使图像缩小,而小于1的数字会使图像缩小。它必须使用比例作为基础尺寸属性的分母。

确保导入必要的框架!

答案 1 :(得分:0)

输入:

imageSize // The image size, for example {1024,768}
maxThumbSize // The max thumbnail size, for example {100,100}

伪代码:

thumbAspectRatio = maxThumbSize.width / maxThumbSize.height
imageAspectRatio = imageSize.width / imageSize.height

if ( imageAspectRatio == thumbAspectRatio )
{
    // The aspect ratio is equal
    // Resize image to maxThumbSize
}
else if ( imageAspectRatio > thumbAspectRatio )
{
    // The image is wider
    // Thumbnail width: maxThumbSize.width
    // Thumbnail height: maxThumbSize.height / imageAspectRatio
} 
else if ( imageAspectRatio < thumbAspectRatio )
{
    // The image is taller
    // Thumbnail width: maxThumbSize.width * imageAspectRatio
    // Thumbnail height: maxThumbSize.height
}