Search code examples
objective-cxcodeuiimageretina-display

Does @2x works on UIImage imageWithNamed?


[self.distanceSlider setThumbImage:[UIImage imageNamed:@"handle-slider"] forState:UIControlStateNormal];

Let's take a look at that code.

If I use retina display, will the image called be handle-slider@2x instead of handle-slider?

Notice that this could raise an issue. Imagined if I load an image for the sole purpose of processing it and I really really want to load handle-slider, or handle-slider@2x? Then having iOS to override my decision and arbitrarily load @2x image will be kind of silly.

On the other hand most of the time, I used UIImage imageNamed to populate a button. In that case, it makes perfect sense to add @2x.

In any case, which path does apple eventually use and if possible, what's the reference?

I searched stackOverflow.

Most answers are inconsistent with one suggesting one or the other.


Solution

  • The documentation for [UIImage imageNamed:] has exactly the information you want to know.

    This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

    On a device running iOS 4 or later, the behavior is identical if the device’s screen has a scale of 1.0. If the screen has a scale of 2.0, this method first searches for an image file with the same filename with an @2x suffix appended to it. For example, if the file’s name is button, it first searches for button@2x. 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.