Search code examples
iosiphoneuiimageassets

iOS get actual size of image from Assets based on device screen size


I am working on an iOS app that uses many images for icons. I have added images to Assets and accessed them from my views.

I need to know the actual size of the image that will be displayed on the screen at run time. When I create UIImage object like this:

let image = UIImage(named: "my_image")

then access its size, I always get the 1x size - on all devices with different screen sizes -. As I know, iOS loads the appropriate image size based on the screen size at run time.

So, how can I get the actual image size that will be rendered on the screen instead of always getting the default size ?


Solution

  • The size of UIImage is in points. To get actual size in pixels, you can multiply it by the scale of your screen - 2.0 or 3.0 for Retina displays - like so

    let scale = UIScreen.main.scale
    let sizeInPixels = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)