Retina display and [UIImage initWithData]

IphoneCocoa TouchUiimage

Iphone Problem Overview


I need to initialise images from raw data downloaded from a server which delivers the correct size of image based on the type of iPhone client.

I know that I should be setting the scale value to be 2.0 on the 640x960 display, however this is a readonly property and cannot be set during the init when using initWithData.

Any ideas?

Iphone Solutions


Solution 1 - Iphone

I'm not aware of anything you can embed in the image data itself to tell the phone that it's a @2x image, but something like this should work:

UIImage * img = ...;
img = [UIImage imageWithCGImage:img.CGImage scale:2 orientation:img.imageOrientation];

Solution 2 - Iphone

Since iOS 6.0 UIImage has method + imageWithData:scale:, you can pass 2.0 as scale for retina.

Solution 3 - Iphone

You can pass [[UIScreen mainScreen] scale] as the scale parameter instead of 2.0f.

Solution 4 - Iphone

Swift3, 4 version

let image = UIImage(data: imageData, scale: UIScreen.main.scale)

Solution 5 - Iphone

put this in your .m if you want or on an imported class (the syntax of c is nicer when calling the function IMAO)

BOOL isRetina(){
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        return [[UIScreen mainScreen] scale] == 2.0;
    }
    return NO;
}

Then when creating the image with the server data:

[UIImage imageWithData:dataFromServer scale:isRetina()?2:1];

Solution 6 - Iphone

AFAIK you don't need to set the scale value yourself. The OS will handle the points to pixel translation for you.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamView Question on Stackoverflow
Solution 1 - Iphonetc.View Answer on Stackoverflow
Solution 2 - IphoneDennis KrutView Answer on Stackoverflow
Solution 3 - IphonePhil LodenView Answer on Stackoverflow
Solution 4 - Iphoneallen huangView Answer on Stackoverflow
Solution 5 - Iphoneuser2387149View Answer on Stackoverflow
Solution 6 - IphoneRengersView Answer on Stackoverflow