下载图像和视网膜显示

时间:2014-02-16 23:32:46

标签: ios image uiviewcontroller retina

如果我从服务器下载一些图像,我应该调整它以支持视网膜设计吗?

如果现在我不能使用 - @ 2x,我该如何设置正确的图像才能显示?

更新:

如果我缓存图像,我需要在下载之后和缓存之前调整图像大小,并缓存2个图像,常规和@ 2x?

1 个答案:

答案 0 :(得分:1)

您的应用应检索视网膜大小的图像。要获得非视网膜大小,您可以手动缩放然后保存它。这里是示例代码:

UIImage *image = [UIImage imageNamed:@"yourRetinaImage@2x.png"];

// set non-retina size from current image
CGSize size = CGSizeMake(image.size.width / 2., image.size.height / 2.);


/** scale the image */

UIGraphicsBeginImageContext(size);

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), image.CGImage);

UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


/** save scaled image */

NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// save with same name but without suffix "@2x"
NSString *filePath = [NSString stringWithFormat:@"%@/%@", basePath, @"yourRetinaImage"];

@try {
    [UIImagePNGRepresentation(scaledImage) writeToFile:filePath options:NSAtomicWrite error:nil];
} @catch (NSException *exception) {
    NSLog(@"error while saving non-retina image with exception %@", exception);
}