Search code examples
iosuiimageviewretina-display

UIImageView content mode and scale factor


I have a programmatically created UIImage image, using this kind of code:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(128, 128), NO, 0.0f);
// Render in context
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Since my context options specify scale of 0, on retina devices it will be set to 2, and I can confirm that on resulting UIImage scale property.

Now, the problem is that this image size is 128x128, scale 2. When I am putting it into UIImageView of size 64x64 and contentMode = Center, it renders my image outside imageview, presumably rendering into 128x128 box without any scaling.

My understanding of retina graphics was that if an image has scale factor 2.0, the it should be rendered at 1/2 size, thus resulting in higher DPI. So I was expecting the image view to render 64x64 image at retina quality. Where am I wrong?


Solution

  • The image will be rendered at the size you give it - 128 x 128. The scale factor means that you will have better rendered curves etc, but the image will still be 128 x 128 points. As stated in the documentation, the size parameter is:

    The size (measured in points) of the new bitmap context. This represents the size of the image returned by the UIGraphicsGetImageFromCurrentImageContext function.

    If you want a retina-quality 64x64 image, use a 64x64 size for your context.