来自URL Retina尺寸的iOS图片?

时间:2015-12-18 09:37:27

标签: ios objective-c iphone swift

我想从Web服务加载一些不同大小的图标(1x,2x和3x) - 但是,当最后没有x2的图像名称时,ios总是将它用作1x。

我已经找到了一些答案,你应该提供一个带有imagename@2x.png的网址 - 这样iOS就可以识别为Retina Image,但是对于3种尺寸的远程图像应该怎样才能正常工作?

在我的Case中,我得到了一个Webservice,它可以提供各种大小的图像。我想用url指定设备的正确大小。

例如:

http://example.com/x2/image.png

http://example.com/x3/image.png

正常情况下使用Images.xcassets提供所有不同的尺寸,但这次我想远程加载图像。如何检查所用设备的尺寸是否正确?我应该要求显示分辨率(或iPhone类型?)来检查应该加载哪个图像?

我如何说这个来自这个网址的图像的UIImageView:

http://example.com/x3/image.png

是3倍(所以不要渲染3倍)?

提前致谢

4 个答案:

答案 0 :(得分:3)

使用[UIScreen mainScreen].scale了解您需要的尺寸。然后加载图片使用此API:+ (nullable UIImage *)imageWithData:(NSData *)data scale:(CGFloat)scale。您可以指定图像的比例。

答案 1 :(得分:0)

尝试使用

[UIScreen mainScreen].scale;

确定屏幕比例。

swift中的

 UIScreen.mainScreen().scale

或使用以下代码:

if ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale == 2.0)){
     // Retina display
}else{
    // non-Retina display
}

答案 2 :(得分:0)

您可以定义一些宏,例如

    #define iPad    UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad

    #define iPhone5OrBelow ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone && [UIScreen mainScreen].bounds.size.height < 667)

    #define iPhone6 ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone && [UIScreen mainScreen].bounds.size.height == 667)

    #define iPhone6Plus ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone && [UIScreen mainScreen].bounds.size.height == 736)

你可以检查任何这个宏,

if (iPhone6 || iPhone5OrBelow)
{
 // use @2ximage.png
}
else 
{
 // use @3ximage.png
}

我希望这会有所帮助。

答案 3 :(得分:-3)

You can check for iPhone.

For Ex :
if(iPHone5 || iPhone5S || iPhone6 || iPhone6S){
// load 2x images.
  use this link http://example.com/x2/image.png
  yourImgView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:yourLinkfor2ximage]];

  }
  else if(iPhone6+ || iPhone6+S ){
  //use this link http://example.com/x3/image.png
    yourImgView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:yourLinkfor3ximage]];
  }