从URL加载时应如何处理视网膜/正常图像?

时间:2011-06-19 18:45:59

标签: ios uiimage retina-display

我了解如何以编程方式从网址为我的应用加载图片,而不是将其打包在应用内,但如何处理1x vs 2x问题?如果需要,我可以从外部源提供这两个版本,但是在设置UIImage时如何处理?

1 个答案:

答案 0 :(得分:7)

我很确定你无法以自动方式远程加载@ 2x图像文件。您将必须测试视网膜显示,然后获得适当的图像,如下所示:

UIImage *image;
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2){
  // @2x
  NSURL *imageURL = [NSURL URLWithString:@"http://www.example.com/images/yourImage@2x.png"];
  NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
  image = [UIImage imageWithData:imageData];
} else {
  // @1x
  NSURL *imageURL = [NSURL URLWithString:@"http://www.example.com/images/yourImage.png"];
  NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
  image = [UIImage imageWithData:imageData];
}
UIImageView *yourImageView = [[UIImageView alloc] initWithImage:image];