Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nicolas-miari
Last active May 22, 2017 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicolas-miari/57409ef4b1a1995cbf5b to your computer and use it in GitHub Desktop.
Save nicolas-miari/57409ef4b1a1995cbf5b to your computer and use it in GitHub Desktop.
UIImage Calculate On-Screen Size (UIImageView: AspectFit)
extension UIImage {
/**
Calculates the resulting size (rendered on screen) of the receiver when it
is displayed within a `UIImageView` instance of bounds size `containerSize`
that has its `contentMode` property set to `.ScaleAspectFit`.
- parameter contanerSize: The size of the hypothetical UIImageView instance
that is to display the receiver on screen.
- returns: the effective size at which the receiver would be rendered on
screen if displayed in said view.
*/
func scaleAspectFitSizeWhenEmbeddedInSize(containerSize: CGSize) -> CGSize {
let imageSize = self.size
let imageRatio = imageSize.width / imageSize.height
let containerRatio = containerSize.width / containerSize.height
if imageRatio < containerRatio {
let scale = containerSize.height / imageSize.height
let width = scale * imageSize.width
return CGSizeMake(width, containerSize.height)
} else{
let scale = containerSize.width / imageSize.width
let height = scale * imageSize.height
return CGSizeMake(containerSize.width, height)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment