Loading a Retina Image from a URL into UIImageView

Showing an image downloaded from a URL and into a UIImageView can be tricky for a retina display.

To understand the problem we have to understand the basics of the iOS coordinate system. The resolution of a iPhone 5 is 640×1136 pixels. When you design a view in a XIB file, the size of the view is set to 320×568 points. A point is a logical unit which maps to a pixel based on a scale factor. For example, for a iPhone 5, the scale factor will be 2. You can get the scale factor using:

[UIScreen mainScreen].scale

Pixel value will be calculated as:

pixel = point x scale

The same scale is applied to images shown in a UIImageView. Let us say that you have a UIImageView that takes up the entire screen. That is, it has a size of 640×1136 pixels in iPhone 5. Now, let’s say, we have an image exactly 640×1136 pixels in size that we wish to show in that UIImageView. If the image file is shipped with the application and has “@2x” in the name, then the image will fit the UIImageView exactly without any scaling. If, however, the file name does not end with “@2x”, iOS will scale the image up by the scale factor (2). This is precisely the problem when you load the image from a URL. In that case, there is no scheme to identify the image as for retina using the “@2x” convention. Here is how you go about fixing the problem.

We will develop a method called loadRetinaImage that will load and process an image from a URL. As a convenience, we will add the method to a category on UIImageView.

@interface UIImageView (URLImage)
- (void) loadRetinaImage: (NSString*) url;

@implementation UIImageView (URLImage)
- (void) loadRetinaImage: (NSString*) urlStr {
    NSURL *url = [NSURL URLWithString:urlStr];
    NSData *data = [NSData dataWithContentsOfURL:url];

    if (data == nil) {
        NSLog(@"Failed to load data from URL: %@", urlStr);


    UIImage *image = [UIImage imageWithData:data];

    //Resample the image to be for retina
    image = [UIImage imageWithCGImage:[image CGImage] 
        scale:[UIScreen mainScreen].scale 

    self.image = image;

The key here is the call to [UIImage imageWithCGImage]. This will set up the image as for retina and is equivalent to having “@2x” at the end of the file name. Now, a 640×1136 pixel image will be shown exactly as is in iPhone 5.

- (void) viewWillAppear:(BOOL)animated {
    [self.imageView loadRetinaImage:@"http://localhost/fat.jpg"];

2 thoughts on “Loading a Retina Image from a URL into UIImageView

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s