2012-09-10 40 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方法或其他。

相关问题