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

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

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.

Learn Swift faster!

Take your Swift learning to the next level: buy the Hacking with Swift e-book and get bonus material to help you learn faster!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>