Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image from URL for Retina Display

I have an application that pulls images from an NSURL. Is it possible to inform the application that they are retina ('@2x') versions (the images are of retina resolution)? I currently have the following but the images appear pixelated on the higher resolution displays:

NSURL *url = [NSURL URLWithString:self.imageURL];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.pictureImageView.image = image;
like image 793
Kevin Sylvestre Avatar asked Feb 12 '11 02:02

Kevin Sylvestre


1 Answers

You need to rescale the UIImage before adding it to the image view.

NSURL *url = [NSURL URLWithString:self.imageURL];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
CGFloat screenScale = [UIScreen mainScreen].scale;
if (image.scale != screenScale)
    image = [UIImage imageWithCGImage:image.CGImage scale:screenScale orientation:image.imageOrientation];
self.pictureImageView.image = image;

It's best to avoid hard-coding the scale value, thus the UIScreen call. See Apple’s documentation on UIImage’s scale property for more information about why this is necessary.

It’s also best to avoid using NSData’s -dataWithContentsOfURL: method (unless your code is running on a background thread), as it uses a synchronous network call which cannot be monitored or cancelled. You can read more about the pains of synchronous networking and the ways to avoid it in this Apple Technical Q&A.

like image 170
Carter Allen Avatar answered Nov 16 '22 02:11

Carter Allen