Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading images from a web server for the retina display iOS

I am downloading images from a webserver for display in a table view in my iOS application using the following code:

NSURL *url = [NSURL URLWithString:[imageArray objectAtIndex:indexPath.row]];
UIImage *myImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
cell.imageView.image = myImage;

The image view is a 60x60 placeholder and 120x120 for the retina display. I am going to assume the user has an iPhone 4. However, if I size the image to 120x120 it does not correct the issue, it just becomes too big for the the imageview. If I size the image to 60x60, on the webserver that is, then the image fits fine but its a little fuzzy. Anyone know how to fix this issue?

Thanks!

like image 831
thebiglebowski11 Avatar asked Dec 30 '25 18:12

thebiglebowski11


1 Answers

Let's first agree that your UIImageView is 60x60 points, meaning 60x60 pixels for a standard display and 120x120 pixels for a retina display.

For a UIImageView at 60x60 points, the image should be 60x60 pixels at scale 1.0 for a standard display and 120x120 pixels at scale 2.0 for a retina display. This means that your UIImage should always have a size of 60x60 points, but should have a different scale depending on the display resolution.

When getting the image data from your server, you should first check the scale of the device's screen and then request the appropriate image size (in pixels), like so:

if ([UIScreen mainScreen].scale == 1.0) {
    // Build URL for 60x60 pixels image
}
else {
    // Build URL for 120x120 pixels image   
}

Then you should put the image data in a UIImage of size 60x60 points, at the appropriate scale:

NSData *imageData = [NSData dataWithContentsOfURL:url];
CFDataRef cfdata = CFDataCreate(NULL, [imageData bytes], [imageData length]);
CGDataProviderRef imageDataProvider = CGDataProviderCreateWithCFData (cfdata);
CGImageRef imageRef = CGImageCreateWithJPEGDataProvider(imageDataProvider, NULL, true, kCGRenderingIntentDefault);
UIImage *image = [[UIImage alloc] initWithCGImage:imageRef 
                                            scale:[UIScreen mainScreen].scale 
                                      orientation:UIImageOrientationUp];
CFRelease (imageRef);
CFRelease (imageDataProvider);
CFRelease(cfdata);

Hope this helps.

like image 95
Spiros Avatar answered Jan 02 '26 10:01

Spiros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!