2012-09-10 38 views
1

我必須從遠程來源爲我的應用程序加載圖標,圖像爲50x50px,以25x25像素顯示在設備上。如何降低遠程服務器加載的非視網膜iPhone的視網膜圖像?

目前圖標在視網膜設備上顯示正確的大小,但在非視網膜設備上顯示的大小是正確大小的兩倍。

供參考:遠程源無法提供非視網膜圖像。

如何縮小非視網膜設備上的UIImage,以便所有設備顯示相同的尺寸?

回答

7

首先檢查,如果你有Retina顯示屏

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2){ 

那麼你就需要對圖像的縮放比例選項設置:

UIImage * scaledImage = [UIImage alloc]; 
scaledImage = [[scaledImage initWithCGImage:[resourceImage CGImage] scale:2.0 orientation:UIImageOrientationUp] autorelease]; 

然後我相信imageView應該縮放並正確顯示

+0

關閉但沒有雪茄。首先,if語句僅檢測視網膜設備,然後再次將作品加倍。我需要反過來,我從遠程源下載高分辨率版本,並且需要縮減規模而不是高檔。 – Camsoft

+1

if語句僅供參考,不作複製,我希望很明顯,您可以反轉它或使用'else'分支。原始代碼縮小圖像,視網膜/非視網膜邏輯是你可以自己做的,對吧?該片段僅顯示縮減的操作和決策規則。 –

+0

你是對的。刪除'if'語句修復了它。我需要始終將我的遠程圖像的比例設置爲2.0,因爲它們都是視網膜大小。 – Camsoft

0

試試這個:

+ (UIImage *) onScaleImage:(UIImage *)image width:(int)width 
{ 
    CGImageRef imageRef = image.CGImage; 

    NSUInteger nWidth = CGImageGetWidth(imageRef); 
    if (nWidth == width) 
     return (nil); 

    double dScaleFactor = (double)width/(double)nWidth; 

    NSUInteger nHeight = (int)((double)CGImageGetHeight(imageRef) * dScaleFactor); 

    CGContextRef context = CGBitmapContextCreate(NULL, width, nHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), CGImageGetColorSpace(imageRef), CGImageGetBitmapInfo(imageRef)); 

    CGContextSetInterpolationQuality(context, kCGInterpolationHigh); 
    CGContextSetShouldAntialias(context, true); 

    CGContextDrawImage (context, CGRectMake(0, 0, width, nHeight), imageRef); 
    CGImageRef imageRefScaled = CGBitmapContextCreateImage(context); 

    // caller must retain 
    UIImage *imageScaled = [[UIImage alloc] initWithCGImage:imageRefScaled]; 

    CGContextRelease (context); 
    CGImageRelease (imageRefScaled); 

    return (imageScaled); 
} 
+0

@A-Live答案肯定是更簡單的解決方案,對於iOS4 +來說,雖然縮放比例是0.5而不是2.0,因爲您要縮小比例。以上版本適用於較舊的iOS版本 – CSmith

+0

我喜歡@A-Live的答案,但它不縮減尺寸,縮小尺寸,甚至0.5放大圖像。 – Camsoft

+0

@CSmith謝謝您的評論,它必須是2.0因子,因爲此參數用於聲明源圖像因子:'在解釋圖像數據時使用的比例因子。' –

0

嗯,你可能只是每次調用換到它在if語句,就像這樣:

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { 
    //do scale stuff here 
} 

爲了避免這種情況,每次輸入,你可以聲明上UIScreen一個類別,它使用內部的代碼 - realScale方法或其他。

相關問題