Skip to content

Instantly share code, notes, and snippets.

@hindalsayyar
Created April 9, 2019 08:37
Show Gist options
  • Save hindalsayyar/955e4ca7ab81f2ddcd43108365cbdb18 to your computer and use it in GitHub Desktop.
Save hindalsayyar/955e4ca7ab81f2ddcd43108365cbdb18 to your computer and use it in GitHub Desktop.
drawImageScaled
func drawImageScaled(_ image: UIImage?) {
print("we are scalling the drawing")
// just draws the image scaled down and centered
let selfRatio: CGFloat = frame.size.width / frame.size.height //change the size later
let imgRatio: CGFloat = (image?.size.width ?? 0.0) / (image?.size.height ?? 0.0)
var rect : CGRect
rect = CGRect(x: 0, y: 0, width: 0, height: 0)
if selfRatio > imgRatio {
// view is wider than img
rect.size.height = frame.size.height
rect.size.width = imgRatio * (rect.size.height ?? 0.0)
} else {
// img is wider than view
rect.size.width = frame.size.width
rect.size.height = (rect.size.width ?? 0.0) / imgRatio
}
rect.origin.x = 0.5 * (frame.size.width - (rect.size.width ?? 0.0))
rect.origin.y = 0.5 * (frame.size.height - (rect.size.height ?? 0.0))
image?.draw(in: rect ?? CGRect.zero)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment