Figuring out an UIImage’s size

Hello everyone – wow, these things are harder to write than I imagined.

Here’s another quick thing that gave me a bit of trouble on a project that I’m working on.
As you all probably know, since Apple introduced Retina displays, we’ve switched to a resolution independent positioning, measured in points, instead of pixel. Each device has a different scale, depending on their resolution (1 for non retina, 2 for retina).

Well on a project that I’ve been working on I’ve had to display images in their respective resolution on a screen and I’ve been getting some of these images from a service and some are loaded from the app’s bundle.

Sounds pretty simple, right?

This as you’d expect returns an image, based on the screen’s scale, where it gets us the non retina version (background) or the retina version (background@2x).
The weird thing here is that for an image that has a resolution of 1024×768, this method always returns an image that has a

size of 1024×768, even for the retina image, which has a resolution of 2048 x 1536.
While the images that came from the bundle always had a size of 1024×768, the images that I received  from the service varied, based on the scale of the device.

You can probably see that this turned out to be an issue for my positioning logic, an issue that I initially thought that was some sort of bug in the implementation of the imageNamed: method.

The usual suspects like StackOverflow didn’t have an answer ready for my  issue, but after some consulting with some of my coworkers and a trip to the Apple documentation of the method (doh).
If it finds a 2x, it loads that image and sets the scale property of the returned UIImage object to 2.0. Otherwise, it loads the unmodified filename and sets the scale property to 1.0.

Well, that says it all, turns out that with images loaded with imageNamed: you have to mind the scale property of the image, if you’d like to have the real size of the image.

Sure enough one multiplication by the scale of the image later, I had my issue resolved.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.