Skip to content

Instantly share code, notes, and snippets.

@heckj
Created March 31, 2019 22:31
Show Gist options
  • Save heckj/9f4ba335772f52051a50ba67da059c26 to your computer and use it in GitHub Desktop.
Save heckj/9f4ba335772f52051a50ba67da059c26 to your computer and use it in GitHub Desktop.
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