Advertisement
Guest User

Untitled

a guest
May 3rd, 2015
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. //
  2. // RBResizer.swift
  3. // Locker
  4. //
  5. // Created by Hampton Catlin on 6/20/14.
  6. // Copyright (c) 2014 rarebit. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10.  
  11. func RBSquareImageTo(image: UIImage, size: CGSize) -> UIImage {
  12. return RBResizeImage(RBSquareImage(image), size)
  13. }
  14.  
  15. func RBSquareImage(image: UIImage) -> UIImage {
  16. var originalWidth = image.size.width
  17. var originalHeight = image.size.height
  18.  
  19. var edge: CGFloat
  20. if originalWidth > originalHeight {
  21. edge = originalHeight
  22. } else {
  23. edge = originalWidth
  24. }
  25.  
  26. var posX = (originalWidth - edge) / 2.0
  27. var posY = (originalHeight - edge) / 2.0
  28.  
  29. var cropSquare = CGRectMake(posX, posY, edge, edge)
  30.  
  31. var imageRef = CGImageCreateWithImageInRect(image.CGImage, cropSquare);
  32. return UIImage(CGImage: imageRef, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation)
  33. }
  34.  
  35. func RBResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
  36. let size = image.size
  37.  
  38. let widthRatio = targetSize.width / image.size.width
  39. let heightRatio = targetSize.height / image.size.height
  40.  
  41. // Figure out what our orientation is, and use that to form the rectangle
  42. var newSize: CGSize
  43. if(widthRatio > heightRatio) {
  44. newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
  45. } else {
  46. newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio)
  47. }
  48.  
  49. // This is the rect that we've calculated out and this is what is actually used below
  50. let rect = CGRectMake(0, 0, newSize.width, newSize.height)
  51.  
  52. // Actually do the resizing to the rect using the ImageContext stuff
  53. UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
  54. image.drawInRect(rect)
  55. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  56. UIGraphicsEndImageContext()
  57.  
  58. return newImage
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement