NEW: Master Swift design patterns with my latest book! >>

How to find an aspect fit image’s size inside an image view

Written by Paul Hudson    @twostraws

All images have a natural size, which is the number of pixels they are wide and high. All image views also have a size, which is whatever width and height they have once their Auto Layout constraints have been resolved.

Things get a little more complex when you place an image inside an image view and make it use aspect fit content mode – the image gets scaled down to fit inside the image view, so that all parts of the image are visible.

If you need to find the size of an aspect fit image inside its image view, I have just the extension for you:

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

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

        let size = CGSize(width: image.width * scale, height: image.height * scale)
        let x = (bounds.width - size.width) / 2.0
        let y = (bounds.height - size.height) / 2.0

        return CGRect(x: x, y: y, width: size.width, height: size.height)
    }
}

You can now use imageView.contentClippingRect to read how read the position and size of the image inside.

Available from iOS 2.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Download for free!

Want a free 75-minute video teaching functional programming, protocol-oriented programming, and more? This is your lucky day!

Click here to visit the Hacking with Swift store >>