2

I'm running into a weird issue with a UIImage displayed within a UIImageView.

If I put a 1024x1024 image within a 173x173 image view with "scale to fill" set, the result is aliased. However, if I put the same image in, then take a screenshot of the imageview and assign it back, the image is displayed perfectly. This bothers me, because the screenshot is supposed to be the exact pixels that I'm seeing within the image view.

On the left is the result of assigning an image directly. On the right is taking a screenshot of the same image and assigning it back. Notice how the Es are jagged on the left, but smooth on the right.

enter image description here

Is this an issue with the content mode of the image view or something that happends during the sreenshot?

    for(UIImageView* placeholderView in self.placeholderImageViews)
    {
//assigning a 1024x1024 image into a smaller image view results in an aliased image here
        placeholderView.image = imageToDisplay;

//this code makes the image appear perfectly scaled down
        if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        {
            UIGraphicsBeginImageContextWithOptions(placeholderView.frame.size, NO, [UIScreen mainScreen].scale);
        }
        else
        {
            UIGraphicsBeginImageContext(placeholderView.frame.size);
        }
        [placeholderView.layer renderInContext:UIGraphicsGetCurrentContext()];
        screenshot = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        //save the result
        placeholderView.image = screenshot;

    }
Alex Stone
  • 46,408
  • 55
  • 231
  • 407

1 Answers1

0

UIImageView scaling sucks; you should always give it an image with exactly the same size of its bounds, so it does not have to scale it down. Check this code and the example.

Swift extension:

extension UIImage{

        // returns a scaled version of the image
        func imageScaledToSize(size : CGSize, isOpaque : Bool) -> UIImage{

            // begin a context of the desired size
            UIGraphicsBeginImageContextWithOptions(size, isOpaque, 0.0)

            // draw image in the rect with zero origin and size of the context
            let imageRect = CGRect(origin: CGPointZero, size: size)
            self.drawInRect(imageRect)

            // get the scaled image, close the context and return the image
            let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return scaledImage
       }
}

Example:

aUIImageView.image = aUIImage.imageScaledToSize(aUIImageView.bounds.size, isOpaque : false)

Set isOpaque to true if the image has no alpha: drawing will have better performance.

J.Williams
  • 1,417
  • 1
  • 20
  • 22