Advertisement
neatekFb

Resize image - Swift 3

Nov 2nd, 2016
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.91 KB | None | 0 0
  1. // Vladimir Zhelnov - neatek.pw - Web/iOS dev
  2. func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
  3.     let size = image.size
  4.     let widthRatio  = targetSize.width  / image.size.width
  5.     let heightRatio = targetSize.height / image.size.height
  6.  
  7.     var newSize: CGSize
  8.     if(widthRatio > heightRatio) {
  9.         newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
  10.     } else {
  11.         newSize = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
  12.     }
  13.  
  14.     let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
  15.     UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
  16.     image.draw(in: rect)
  17.     let newImage = UIGraphicsGetImageFromCurrentImageContext()
  18.     UIGraphicsEndImageContext()
  19.     return newImage!
  20. }
  21. // usage: let littleImage = ResizeImage(image: chosenImage, targetSize: CGSize(width: 800, height: 500))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement