UIImageView resizing to eliminate blank space IOS

Viewed 2821

My UIImageView is in aspect fit mode which leaves blank space beneath the actual image.

UIImageView displayment

The blue space is what I want to eliminate so the imageView wraps the image (if only I had wrap content). Seemed like an easy task but I soon realized that the image is in aspect fit so the image view changes the width and height of the image but then I would have to make a calculation on the image view based on that altered image which would make a never ending loop of shrinking the image.

UIImageView in the app

I just want to remove the blank space to make it look more concise. Full project at GitHub: https://github.com/sak6lab/Closet-Space

2 Answers

So based on Fogmeister answer,instead of width, change it to height and then height to width for the view

let newsize = self.feedImage.contentClippingRect

self.feedImage.heightAnchor.constraint(equalTo: self.feedImage.widthAnchor, multiplier:newsize.width / newsize.height).isActive = true

where newsize is the CGRect after we scale with .scaleaspectfit Note the below extension from https://www.hackingwithswift.com/example-code/uikit/how-to-find-an-aspect-fit-images-size-inside-an-image-view

extension UIImageView {
    var contentClippingRect: CGRect {
    guard let image = image else { return bounds }
    guard contentMode == .scaleAspectFit else { return bounds }
    guard image.size.width > 0 && image.size.height > 0 else { return bounds }

    let scale: CGFloat
    if image.size.width > image.size.height {
        scale = bounds.width / image.size.width
    } else {
        scale = bounds.height / image.size.height
    }

    let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
    let x = (bounds.width - size.width) / 2.0
    let y = (bounds.height - size.height) / 2.0
    //print ("image resizing[width=\(size.width), height=\(size.height)")
    return CGRect(x: x, y: y, width: size.width, height: size.height)
    }
}
Related