Skip to content

Instantly share code, notes, and snippets.

@viccc
Created October 17, 2016 18:01
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 viccc/1f223e4da309f2a5544b32b01d804e63 to your computer and use it in GitHub Desktop.
Save viccc/1f223e4da309f2a5544b32b01d804e63 to your computer and use it in GitHub Desktop.
func size(_ imageSize: CGSize, constrainedToSize maxSize: CGSize) -> CGSize {
if maxSize.width > 0 && maxSize.height > 0 && (maxSize.width < imageSize.width || maxSize.height < imageSize.height)
{
let constrainedSize: CGSize
let constrainedHeight = min(imageSize.height, maxSize.height)
let scaleProportionalToHeight = constrainedHeight / imageSize.height
let sizeProportionalToHeight = CGSize(width: round(imageSize.width * scaleProportionalToHeight), height: constrainedHeight)
let constrainedWidth = min(imageSize.width, maxSize.width)
let scaleProportionalToWidth = constrainedWidth / imageSize.width
let sizeProportionalToWidth = CGSize(width: constrainedWidth, height: round(imageSize.height * scaleProportionalToWidth))
if (scaleProportionalToWidth > scaleProportionalToHeight)
{
if sizeProportionalToWidth.height > maxSize.height {
constrainedSize = sizeProportionalToHeight
} else {
constrainedSize = sizeProportionalToWidth
}
}
else
{
if sizeProportionalToHeight.width > maxSize.width {
constrainedSize = sizeProportionalToWidth
} else {
constrainedSize = sizeProportionalToHeight
}
}
return constrainedSize
}
return imageSize
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment