Skip to content

Instantly share code, notes, and snippets.

@yashthaker7
Last active September 9, 2020 06:48
Show Gist options
  • Save yashthaker7/7aefd3355372683415454d2873a873c3 to your computer and use it in GitHub Desktop.
Save yashthaker7/7aefd3355372683415454d2873a873c3 to your computer and use it in GitHub Desktop.
This extension is to get image's aspectFill frame
extension UIImageView {
var getImageAspectFillFrame: CGRect? {
guard let image = image, frame != .zero else { return nil }
let imageSize = image.size
if imageSize.width > imageSize.height { // landscape
return calcMaxWidth(imageSize, frame.size)
} else if imageSize.height > imageSize.width { // portrait
return calcMaxHeight(imageSize, frame.size)
} else { // square
if frame.width > frame.height {
return calcMaxHeight(imageSize, frame.size)
} else if frame.height > frame.width {
return calcMaxWidth(imageSize, frame.size)
} else {
return CGRect(origin: .zero, size: frame.size)
}
}
}
func calcMaxWidth(_ imageSize: CGSize, _ frameSize: CGSize) -> CGRect {
var height = frameSize.height
var width = imageSize.width * height / imageSize.height
if width.isNaN {
width = 0.0
} else if width < frameSize.width {
width = frameSize.width
height = imageSize.height * width / imageSize.width
}
let pos = CGPoint(x: (frameSize.width/2) - (width/2), y: (frameSize.height/2) - (height/2))
return CGRect(origin: pos, size: CGSize(width: width, height: height))
}
func calcMaxHeight(_ imageSize: CGSize, _ frameSize: CGSize) -> CGRect {
var width = frameSize.width
var height = imageSize.height * width / imageSize.width
if height.isNaN {
height = 0.0
} else if height < frameSize.height {
height = frameSize.height
width = imageSize.width * height / imageSize.height
}
let pos = CGPoint(x: (frameSize.width/2) - (width/2), y: (frameSize.height/2) - (height/2))
return CGRect(origin: pos, size: CGSize(width: width, height: height))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment