2012-06-20 15 views
1

我的應用程序處理從相機拍攝的圖像。我希望能夠將這些圖像調整爲縮略圖大小,以便我可以在表格視圖的單元格內顯示它們。您可以在保留比例的同時在iOS上調整UIImage大小嗎?縮略圖生成

「實時」調整大小似乎相當緩慢,因此我打算在用戶將它們導入應用程序時將其調整大小,並將全尺寸和縮略圖存儲在業務對象上,使用縮略圖如表意見

這是我用來生成縮略圖代碼:

#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,所以我需要調整圖像的大小以適應它,而不會扭曲它。

任何指針都會很棒!

+1

爲什麼不調整大小使新的寬度和高度更小(寬度或高度)並相應地考慮其他因素,那麼只需將uiimageview的屬性設置爲方向適合或填充? – Pochi

+0

我的意思是,調整到100的值,忘了100 haha​​ – Pochi

回答

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 
} 
3

我意識到這是一個古老的線程,但是如果你偶然發現這一點,有現在在iOS6的一個更簡單的方法。在Apple的文檔中找到以下內容之前,我花了很多時間嘗試使用此解決方案。

二者必選其一:

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

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

如果你想用它來從一個名爲「圖像」的UIImage做一個縮略圖,你可以用一行代碼:

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

我發現大於1的數字會縮小圖像,小於1的數字會將其展開。它必須將該比例用作基礎大小屬性的分母。

確保您導入必要的框架!

+0

也是方便的是'imageWithData:scale:'。 –

相關問題