Created
March 31, 2019 22:31
-
-
Save heckj/9f4ba335772f52051a50ba67da059c26 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
let scaleByWidth = bounds.width / image.size.width | |
let scalebyHeight = bounds.height / image.size.height | |
// attempt to scale by width, and see if the height exceeds the bounds | |
if image.size.height * scaleByWidth < bounds.height { | |
// we're within the bounds, so it's the right scale | |
scale = scaleByWidth | |
} else { | |
// the image exceeded the bounds, so scale by the height ratio instead | |
scale = scalebyHeight | |
} | |
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 | |
return CGRect(x: x, y: y, width: size.width, height: size.height) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment