Llg Llg - 1 month ago 7
Swift Question

iOS: display an image with the same quality for all screens

My view in the storyboard contains an imageView having for the constraints top= 0, height= 55, width= 230 and centred horizontally. Using the "view as" option in the last version of Xcode, I realise that the display of the image and its quality are not the same for all the screens. In the iPhone 4s the quality is good but the image same big. Otherwise, in the iPhone 6s plus screen, I see that the image size is good for the screen but the quality isn't well.

How the image can be displayed the same way in all the screens? Can anyone please give me the right constraints to resolve this?

Answer

Depending on the device's screen, you should define various representation of the image.

From the Apple Developer portal:

iOS uses a coordinate system to place content onscreen. This coordinate system is based on measurements in points, which map to pixels in the display.

If you define all three image resolutions (normal/@1x, @2x, @3x), you should be good to go.

What is important, that the normal or @1x should have the following parameters: height: 55, width: 230

The @2x should be twice the size of @1x: height: 110, width:460

The @3x should be three times the size of @1x: height: 165, width:690

Lets assume you image is called my_image, and it is a png.

  • the @1x should be called: my_image.png
  • the @2x should be called: my_image@2x.png
  • the @3x should be called: my_image@3x.png

Add all these images to the Assets.xcassets. Click on Assets.xcassets. Once it is opened, you should see a + sign on the left hand side.

enter image description here

Tap on the + sign and give a name to you image:

enter image description here

And insert them into these slots:

enter image description here

Now, when you are trying to use this image, you can just simply say in Swift:

let image = UIImage(named: "my_image")