Search code examples
iosswift

UIImage scale factor not taken account of in UITabBarItem image


I am cropping a UIImage by using UIGraphicsGetCurrentContext and then saving it to cache. I then show that UIImage as the image of one of my tab bar items. This works, however, the scale factor of the image is an issue. If I use UIGraphicsBeginImageContextWithOptions with the scale set to zero, this correctly crops it using the scale factor of the screen. However, when I set the UITabBarItem image, it seems to ignore the fact that the image should be scaled.

My code for scaling:

extension UIImage {
    func scaledImage(withSize size: CGSize, withBorder: Bool) -> UIImage {
        let imageView = UIImageView(image: self)
        imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        imageView.contentMode = .scaleAspectFit
        let layer = imageView.layer
        layer.masksToBounds = true
        layer.cornerRadius = size.width/2
        
        if withBorder {
            layer.borderColor = Styles.Colours.blue.colour.cgColor
            layer.borderWidth = 2
        }
        
        UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 1) // Notice I've set the scale factor to 1 here for now. If I set it to 0 the image is too large on the tab bar
        defer { UIGraphicsEndImageContext() }
        layer.render(in: UIGraphicsGetCurrentContext()!)
        return UIGraphicsGetImageFromCurrentImageContext()!
    }
}

Used like this:

let defaultImage = image?.scaledImage(withSize: CGSize(width: 25, height: 25), withBorder: false)

Then I set the tab bar item like this:

self.tabBar.items?.last?.image = defaultImage.withRenderingMode(.alwaysOriginal)

If I was to set a UIImage from my Assets, then it would take into account the scale factor. How do I fix this?


Solution

  • Solved it by converting the UIImage to one that specifically defines the scale like this:

    let scaledSelectedImage = UIImage(data: UIImagePNGRepresentation(image)!, scale: UIScreen.main.scale)